[英]Instantiate a class that derives from MonoBehaviour
Is there a way to instantiate a class that derives from MonoBehaviour such as the example bellow without getting the warning: "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" 有没有一种方法可以实例化一个从MonoBehaviour派生的类,例如下面的示例,而没有收到警告:“您正在尝试使用'new'关键字创建MonoBehaviour。这是不允许的。MonoBehaviours只能使用AddComponent( )。或者,您的脚本可以继承ScriptableObject或根本不继承基类。”
Example: 例:
public class e1506131012test2 : MonoBehaviour
{
Move move = new Move();
//Move move = gameObject.GetComponent<Move>();
void Update()
{
move.Printing();
}
}
public class Move : MonoBehaviour
{
public int number = 5;
public void Printing()
{
print(number);
}
}
There are a few ways you can do this, the easiest is probably to use AddComponent
as the error message suggests: 有几种方法可以执行此操作,最简单的方法可能是使用AddComponent
如错误消息所示:
Move move;
void Start()
{
move = gameObject.Addcomponent<Move>();
}
The reason you can't just new
up an object that derives from MonoBehaviour is that such objects must be a component of a GameObject
. 您不能仅仅new
从MonoBehaviour派生的对象的原因是,此类对象必须是GameObject
的组成部分。 As such, whenever you create one you have to ensure that it is added in a valid way. 因此,无论何时创建一个,都必须确保以有效方式添加它。
Just don't derive it from MonoBehaviour. 只是不要从MonoBehaviour派生它。
public class Move
{
public int number = 5;
public void Printing()
{
print(number);
}
}
And if it really must be a MonoBehaviour, that means you probably have it on a prefab, in which case you use Instantiate(). 而且,如果它确实必须是MonoBehaviour,则意味着您可能将其放在预制件上,在这种情况下,您可以使用Instantiate()。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.