问题
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:
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:
回答1:
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);
}
回答2:
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);
}
来源:https://stackoverflow.com/questions/44692366/activeself-return-true-and-gameobject-is-false