为什么团结一致我收到警告:您正在尝试使用'new'关键字创建MonoBehaviour?

mos*_*alf -4 c# unity-game-engine

完整的警告信息:

您正在尝试MonoBehaviour使用new关键字创建一个.这是不允许的.MonoBehaviours只能添加使用AddComponent().或者,您的脚本可以继承ScriptableObject或根本不继承基类

在这两个脚本中,我没有使用new关键字:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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!");
    }
}
Run Code Online (Sandbox Code Playgroud)

ryg*_*go6 9

最好不要将MonoBehaviours视为传统意义上的C#对象.他们应该被认为是他们自己独特的东西.它们在技术上是Unity所基于的实体组件系统架构的"组件"部分.

因此,MonoBehaviour是一个组件,它不能存在于GameObject中.因此,仅使用"new"关键字创建MonoBehaviour不起作用.要创建MonoBehaviour,必须在GameObject上使用AddComponent.

除此之外,您无法在类范围内创建新的GameObject.一旦游戏开始,它必须在一个方法中完成,这样做的理想场所是Awake.

你想做的是

DetectPlayer dp;

private void Awake()
{
    GameObject gameObject = new GameObject("DetectPlayer");
    dp = gameObject.AddComponent<DetectPlayer>();
}
Run Code Online (Sandbox Code Playgroud)