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.
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);
}
}
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).Be careful how you name your variables. There is a local variable inherited from
MonoBehaviour
andComponent
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
notgameObject
.The O is not capitalized.You can also simplify this to:
Finally, I suggest you rename the parameter variable
GameObject gameobject
toGameObject objToToggle
so that you won't make this mistake in the future again.