问题
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