为什么在 unity 中我收到警告:您正在尝试使用“new"关键字创建 MonoBehaviour? [英] Why in unity i'm getting the warning: You are trying to create a MonoBehaviour using the 'new' keyword?
问题描述
完整的警告信息:
您正在尝试使用 new
关键字创建一个 MonoBehaviour
.这是不允许的.MonoBehaviours
只能使用 AddComponent()
添加.或者,您的脚本可以从 ScriptableObject
继承或根本没有基类
You are trying to create a
MonoBehaviour
using thenew
keyword. This is not allowed.MonoBehaviours
can only be added usingAddComponent()
. Alternatively, your script can inherit fromScriptableObject
or no base class at all
并且在两个脚本中我都没有使用 new
关键字:
And in both scripts I'm not using the new
keyword:
DetectPlayer
脚本:
public class DetectPlayer : MonoBehaviour
{
private int counter = 0;
private void OnGUI()
{
GUI.Box(new Rect(300, 300, 200, 20),
"Times lift moved up and down " + counter);
}
}
Lift
脚本:
public class Lift : MonoBehaviour
{
private bool pressedButton = false;
private DetectPlayer dp = new DetectPlayer();
private void OnGUI()
{
if (pressedButton)
GUI.Box(new Rect(300, 300, 200, 20), "Press to use lift!");
}
}
推荐答案
最好不要将 MonoBehaviours 视为传统意义上的 C# 对象.他们应该被认为是他们自己独特的东西.从技术上讲,它们是 Unity 所基于的实体组件系统架构的组件"部分.
It is best to not think of MonoBehaviours as C# objects in the traditional sense. They should be considered their own unique thing. They are technically the 'Component' part of the Entity Component System architecture which Unity is based upon.
因此,MonoBehaviour 是一个组件,它不能存在于游戏对象上.因此,仅使用 'new' 关键字创建 MonoBehaviour 是行不通的.要创建 MonoBehaviour,您必须在 GameObject 上使用 AddComponent.
As such, a MonoBehaviour being a Component, it cannot exist without being on a GameObject. Thus creating a MonoBehaviour with just the 'new' keyword doesn't work. To create a MonoBehaviour you must use AddComponent on a GameObject.
此外,您不能在类范围内创建新的游戏对象.一旦游戏运行,它必须在一个方法中完成,一个理想的地方是在 Awake 中.
Further than that you cannot create a new GameObject at class scope. It must be done in a method once the game is running, an ideal place to do this would be in Awake.
你想做的是
DetectPlayer dp;
private void Awake()
{
GameObject gameObject = new GameObject("DetectPlayer");
dp = gameObject.AddComponent<DetectPlayer>();
}
这篇关于为什么在 unity 中我收到警告:您正在尝试使用“new"关键字创建 MonoBehaviour?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!