统一(对象名称与游戏对象)

Unity (Object name vs gameobject)

我正在在线学习 class 使用 unity 进行游戏开发,讲师有时会含糊不清。我的印象是使用游戏对象与使用游戏对象名称(在本例中为 MusicPlayer)相同,但是当我尝试将 MusicPlayer 实例替换为游戏对象实例时,我得到错误 CS0246:类型或命名空间名称`游戏对象' 找不到。您是否缺少 using 指令或程序集引用?我只是想了解两者之间的区别。提前谢谢你。

using UnityEngine;
using System.Collections;
public class MusicPlayer : MonoBehaviour {
static MusicPlayer instance = null;
 void Awake(){
    if (instance != null){
    Destroy(gameObject);
    Debug.Log("Duplicate MusicPlayer Destroyed");
    }

    else{
    instance = this;
    GameObject.DontDestroyOnLoad(gameObject);
    Debug.Log("Original MusicPlayer Created!");
    }
}
}

这是我遇到错误的代码:

using UnityEngine;
using System.Collections;
public class MusicPlayer : MonoBehaviour {
public static gameobject instance = null;

void Awake(){
    if (instance != null){
    Destroy(gameObject);
    Debug.Log("Duplicate MusicPlayer Destroyed");
    }

    else{
    instance = this;
    GameObject.DontDestroyOnLoad(gameObject);
    Debug.Log("Original MusicPlayer Created!");
    }
}
}

gameObjectGameObject有区别。注意第二个中大写的"G"。

GameObject 是一个 class。您可以像这样创建它的实例:

GameObject myobject = new GameObject("PhilipBall");

或者您可以将其设为 public 变量并从编辑器中分配它:

public  GameObject myobject;

gameObject 是从 GameObject 创建的变量。它的声明类似于上面的 myobject 变量示例。

您看不到它的原因是因为它是在名为 Component 的 class 中声明的。然后一个名为 Behaviour 的 class 继承自那个 Component class。还有一个名为 MonoBehaviour 的 class 继承自 Behaviour class。最后,当您执行 public class MusicPlayer : MonoBehaviour 时,您的名为 MusicPlayer 的脚本继承自 MonoBehaviour。因此,您继承了 gameObject 变量并可以使用它。


GameObject class 的 gameObject 变量类型,用于引用此脚本附加到的游戏对象。

I want to know why I cannot use gameObject and must use the name of the gameObject

你真的可以做到。只需将 public static gameobject instance = null; 替换为 public static GameObject instance = null;,然后将 instance = this; 替换为 instance = this.gameObject;

public class MusicPlayer : MonoBehaviour
{
    public static GameObject instance = null;

    void Awake()
    {
        if (instance != null)
        {
            Destroy(gameObject);
            Debug.Log("Duplicate MusicPlayer Destroyed");
        }

        else
        {
            instance = this.gameObject;
            GameObject.DontDestroyOnLoad(gameObject);
            Debug.Log("Original MusicPlayer Created!");
        }
    }
}

当你使用它时,你指的是这个脚本 MusicPlayer。当您使用 this.gameObject 时,您指的是此脚本附加到的游戏对象。

为什么 public static GameObject instance = null; 没有被你的导师使用?

这是因为他们想要访问 MusicPlayer 脚本变量,运行-time.They 期间的函数不需要 GameObject。现在,这可以通过游戏对象来完成,但您必须执行额外的步骤,例如使用 GetComponent 才能在该脚本中使用变量或调用函数。

例如,您在该脚本中有一个名为 "runFunction" 的函数并且您想要调用它。对于第一个示例,您可以这样做:

MusicPlayer.instance.runFunction();

对于第二个例子,你必须做:

MusicPlayer.instance.GetComponent<MusicPlayer>().runFunction();

这是最大的区别,还要注意 GetComponent 很昂贵。