gpt4 book ai didi

c# - 统一(对象名称与游戏对象)

转载 作者:太空宇宙 更新时间:2023-11-03 22:56:51 27 4
gpt4 key购买 nike

我正在参加使用 Unity 进行游戏开发的在线类(class),讲师有时会含糊不清。我的印象是使用游戏对象与使用游戏对象名称(在本例中为 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是一个类。您可以像这样创建它的实例:

GameObject myobject = new GameObject("PhilipBall");

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

public  GameObject myobject;

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

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


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

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 时,您指的是此脚本附加到的这个 GameObject。

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

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

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

MusicPlayer.instance.runFunction();

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

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

这是最大的区别,还要注意 GetComponent 的开销很大。

关于c# - 统一(对象名称与游戏对象),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44992383/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com