为什么我会得到统一的警告:您正在尝试使用'new'关键字创建MonoBehaviour? [英] Why in unity i'm getting the warning: You are trying to create a MonoBehaviour using the 'new' keyword?

查看:2729
本文介绍了为什么我会得到统一的警告:您正在尝试使用'new'关键字创建MonoBehaviour?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

完整的警告消息:

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

You are trying to create a MonoBehaviour using the new keyword. This is not allowed. MonoBehaviours can only be added using AddComponent(). Alternatively, your script can inherit from ScriptableObject 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,如果不存在于GameObject上就不可能存在.因此,仅使用'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.

此外,您不能在类范围内创建新的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>();
}

这篇关于为什么我会得到统一的警告:您正在尝试使用'new'关键字创建MonoBehaviour?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆