按键时切换GameObject /组件活动状态

时间:2018-05-23 21:26:15

标签: c# unity3d

void Update () 
{
    if(Input.GetKeyDown(KeyCode.Tab))
    {
        ObjectOne.SetActive(true)
        Debug.Log("set");
    } 

    Debug.Log ("Update is called");
}

当我再次按Tab键时,我想切换SetActive,当我再按一次时,我想切换为真。

1 个答案:

答案 0 :(得分:4)

如果您只想在每次按Tab键时切换GameObject的激活和取消激活,请在按下Tab键时使用ObjectOne.activeSelf获取当前状态。翻转!然后将该翻转的值传递给SetActive函数。

public GameObject ObjectOne;

void Update()
{
    if (Input.GetKeyDown(KeyCode.Tab))
    {
        //Get current State
        bool currentState = ObjectOne.activeSelf;

        //Flip it
        currentState = !currentState;

        //Set the current State to the flipped value
        ObjectOne.SetActive(currentState);
    }
}

这也可以在一行代码中完成:

void Update()
{
    if (Input.GetKeyDown(KeyCode.Tab))
        ObjectOne.SetActive(!ObjectOne.activeSelf);
}

如果这是一个组件,请改用Behaviour.enabled。整个切换的事情仍然是一样的。最好是缓存组件而不是在Update函数中获取它,但在简单的情况下,我不会在下面的示例中。

public GameObject ObjectOne;

void Update()
{
    if (Input.GetKeyDown(KeyCode.Tab))
    {
        Renderer rdr = ObjectOne.GetComponent<Renderer>();

        //Get current State
        bool currentState = rdr.enabled;

        //Flip it
        currentState = !currentState;

        //Set the current State to the flipped value
        rdr.enabled = currentState;
    }
}