Instantiate a class that derives from MonoBehaviour [duplicate]

允我心安 提交于 2021-02-16 20:25:25

问题


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"

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

回答1:


There are a few ways you can do this, the easiest is probably to use AddComponent as the error message suggests:

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. As such, whenever you create one you have to ensure that it is added in a valid way.




回答2:


Just don't derive it from 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().



来源:https://stackoverflow.com/questions/30849855/instantiate-a-class-that-derives-from-monobehaviour

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!