【发布时间】: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关键字。你真的应该在发布之前查看你的代码。另外,只包含相关的代码。