activeSelf return true 且 gameobject 为 false

activeSelf return true and gameobject is false

所以我有一个名为 menuView 的游戏对象。我创建了 toogleGameobject 的脚本,它很简单 - 检查它是否是 selfActive,如果它被设置为 false,如果它是 false 则将它设置为 true。问题是由于某种原因它没有工作。然后在该函数中我设置 Debug.Log(selfActive) 并在我的控制台中 returns 它是真的但我的游戏对象是假的。

图片如下:

我通过按钮调用脚本并且脚本需要参数gameObject所以我通过检查器分配它。

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);
    }
}

这里我分配并调用游戏对象:

注意变量的命名方式。有一个从 MonoBehaviourComponent 继承的局部变量名为“gameObject”。

您使用 gameObject 来引用此脚本附加到的游戏对象。

脚本附加到的 GameObject 是您当前正在切换的 on/ff 不是 传递给 toogleGameObject函数。

传递给 toogleGameObject 函数的 GameObject 被命名为 gameobject 而不是 gameObjectO 没有大写。

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);
    }
}

您还可以将其简化为:

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

最后,建议大家将参数变量GameObject gameobject重命名为GameObject objToToggle,这样以后就不会再犯这个错误了。

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

如我所料,您在切换游戏对象之前调用了Debug.Log ,因此,Debug.Log告诉您游戏对象的相反状态(因为您之后立即更改其状态)。

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

    gameobject.SetActive(!gameobject.activeSelf);

    Debug.Log("After toggle : " + gameobject + " " + gameobject.activeSelf);
}