Hello Guys, I have a class called OBJ writte in C# and I derived it from a MonoBehaviour". In another a javascript I call
var obj = new OBJ();
which causes the following 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
UnityEngine.MonoBehaviour:.ctor()
OBJ:.ctor(String, Boolean)
createObjects:Start() (at Assets/createObjects.js:20)
can you tell me what’s the problem?
Thanks
Giancarlo
If it extends MonoBehaviour, then you have to use the AddComponent method to instantiate the script and attach it to an existing GameObject.
If you want an object unattached to any GameObjects or not existing in the world don’t use MonoBehaviour. look at ScriptableObject or just don’t inherit. Components and all child parts are designed to be attached to GameObjects. If you use new, it’ll never initialize your class, nor will it call Awake, Start, Update, FixedUpdate, and all other Monobehaviour functions, removing the need for a MonoBehaviour.
Uhm I guess I’m gonna adopt Ntero suggestion but FizixMan, really thank you as yo made my mind clear. The purpose of my OBJ script is just to create a GameObject with a new Muesh ont the fly so I guess I’ll get rid of the inheritance
super thank you!