Unity(对象名称与游戏对象)

菲利普·维索

我正在上一堂使用 Unity 进行游戏开发的在线课程,讲师有时可能会含糊其辞。我的印象是使用游戏对象与使用游戏对象名称(在本例中为 MusicPlayer)相同,但是当我尝试用游戏对象实例替换 MusicPlayer 实例时,我收到错误CS0246:类型或命名空间名称`gameobject ' 找不到。您是否缺少 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!");
    }
}
}
程序员

gameObject之间有区别GameObject注意第二个中大写的“G”。

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

GameObject myobject = new GameObject("PhilipBall");

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

public  GameObject myobject;

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

您看不到它的原因是因为它是在名为Component. 然后一个名为的类BehaviourComponent该类继承还有另一个名为MonoBehaviourBehaviour继承自该类。最后,您的名为 MusicPlayer 的脚本从MonoBehaviour您执行时继承public class MusicPlayer : MonoBehaviour因此,您可以继承该gameObject变量并可以使用它。


GameObjectgameObject变量类型,用于引用此脚本附加到的 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在运行时访问脚本变量和函数。他们不需要游戏对象。现在,这可以通过 GameObject 来完成,但您必须执行额外的步骤,例如 usingGetComponent以便在该脚本中使用变量或调用函数。

例如,您在该脚本中有一个名为“runFunction”的函数,并且您想调用它。对于第一个示例,您可以执行以下操作:

MusicPlayer.instance.runFunction();

对于第二个示例,您必须执行以下操作:

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

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章