Is there a way to instantiate classes that inherit from MonoBehaviour?

I wish to instantiate a class inherite from MonoBehaviour class in a similar way than the example bellow.

Is there a way to do it without getting the warning message (“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”).

public classe Test : MonoBehaviour
{
Move move = newMove();

void Update()
{
move.Printing ();
}

}

public class Move : MonoBehaviour
{
public int number = 5;

public void Printing()
{
print(number);
}
}

thank you.

Why does Move inherit from MonoBehaviour? Just make it a plain C# class.

If you don’t need to be attached to a game object, you don’t need to inherit from MonoBehaviour.

You only need to inherit from MonoBehaviour if you need access to Unities Update/Start etc. messaging system. And then yes, you need to follow the warning and add yourself using AddComponent

1 Like

Did you read the error message? It says ‘use AddComponent’. So the obvious answer to this is to use AddComponent.

Or as @Korno says, don’t inherit from MonoBehaviour.

1 Like