【问题标题】:Why in unity i'm getting the warning: You are trying to create a MonoBehaviour using the 'new' keyword? [closed]为什么统一我收到警告:您正在尝试使用“新”关键字创建 MonoBehaviour? [关闭]
【发布时间】:2016-11-16 19:20:29
【问题描述】:

完整的警告信息:

您正在尝试使用new 关键字创建MonoBehaviour。这是不允许的。 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);
    }
}

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!");
    }
}

【问题讨论】:

  • 你绝对在使用new关键字:DetectPlayer dp = new DetectPlayer();
  • Unity 不喜欢使用new 创建MonoBehavior 派生对象。它希望您使用 Instantiate 来代替它的内部管理工作正常。
  • 您使用了 3 次 new 关键字。你真的应该在发布之前查看你的代码。另外,只包含相关的代码。

标签: c# unity3d


【解决方案1】:

最好不要将 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>();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-28
    • 1970-01-01
    • 1970-01-01
    • 2013-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多