activeSelf return true and gameobject is false

2019-09-13 18:08发布

So i have gameobject called menuView. I created script that toogleGameobject and it is simple - check if it is selfActive, if it is then set to false and if it false then set it to true. Problem is that for some reason it was not working. Then inside that function i set Debug.Log(selfActive) and in my console it returns that it is true but my gameobject is false.

Here is image: image

I am calling script by button and script need parameter gameObject so I assign it through inspector.

public void toogleGameObject(GameObject gameobject)
{
    Debug.Log(gameobject + " " + gameObject.activeSelf);

    //In image above this down was under comment, so only Debug.Log was caled with function
    if(gameObject.activeSelf == true)
    {
        gameObject.SetActive(false);
    }
    else
    {
        gameObject.SetActive(true);
    }
}

Here i assign and call gameobject:Image

2条回答
The star\"
2楼-- · 2019-09-13 18:48

As I expected, you call Debug.Log before toggling your gameobject, thus, the Debug.Log tells you the opposite state of your gameobject (since you change its state right after).

public void toogleGameObject(GameObject gameobject)
{
    //Debug.Log("Before toggle : " + gameobject + " " + gameobject.activeSelf);

    gameobject.SetActive(!gameobject.activeSelf);

    Debug.Log("After toggle : " + gameobject + " " + gameobject.activeSelf);
}
查看更多
狗以群分
3楼-- · 2019-09-13 18:53

Be careful how you name your variables. There is a local variable inherited from MonoBehaviour and Component named "gameObject".

You use that gameObject to refer to the GameObject that this script is attached to.

That GameObject the script is attached to is what you are currently toggling on/ff not the one that is passed to the toogleGameObject function.

The GameObject that is passed to the toogleGameObject function is named gameobject not gameObject.The O is not capitalized.

public void toogleGameObject(GameObject gameobject)
{
    Debug.Log(gameobject + " " + gameobject.activeSelf);

    //In image above this down was under comment, so only Debug.Log was caled with function
    if(gameobject.activeSelf == true)
    {
        gameobject.SetActive(false);
    }
    else
    {
        gameobject.SetActive(true);
    }
}

You can also simplify this to:

public void toogleGameObject(GameObject gameobject)
{
    Debug.Log(gameobject + " " + gameobject.activeSelf);
    gameobject.SetActive(!gameobject.activeSelf);
}

Finally, I suggest you rename the parameter variable GameObject gameobject to GameObject objToToggle so that you won't make this mistake in the future again.

public void toogleGameObject(GameObject objToToggle)
{
    Debug.Log(objToToggle + " " + objToToggle.activeSelf);
    objToToggle.SetActive(!objToToggle.activeSelf);
}
查看更多
登录 后发表回答