- Home /
Is it possible to use scripts without MonoBehaviour on GameObjects?
I'm researching random level generation in Unity for a school project and I decided to use a tutorial from a youtuber named Six Dot Studios. In the video description he linked his project, and I decided to check it out, but it doesn't work.
His "Room" script doesn't derive from MonoBehaviour and adding MonoBehaviour doesn't seem to make it work either, returning this error:
"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() Room:.ctor(Vector2, Int32) (at Assets/Generation scripts/Room.cs:10) LevelGeneration:CreateRooms() (at Assets/Generation scripts/LevelGeneration.cs:56) LevelGeneration:Start() (at Assets/Generation scripts/LevelGeneration.cs:23)"
I can add more info if needed and the scripts can all be downloaded in the video desc, but my question is as follows
TL;DR: Is it possible to create a secondary, non-MonoBehaviour C# script and then add it to a GameObject through a Primay C# one?
Answer by xxmariofer · Mar 01, 2019 at 12:18 PM
first, why do you need to derive from monobehaviour? MonoBehaviour scripts are special scripts that are attached to GameObjects, those scripts can not be created like non-moonobehaviours scripts with the new key, if you want to "add his original non-MonoBehaviour Room script in the level generation script" you need to find the reference to the object that has that script. you can drag and drop from the inspector the reference or find it in runtime using https://docs.unity3d.com/ScriptReference/Resources.FindObjectsOfTypeAll.html for example or any other way like gameobject.find.
Because the "Room script" is needed to assign doors on different sides of the rooms, (Cardinal direction combinations, think Binding of Isaac or Legend of Zelda). In the tutorial the script is attatched to the room GameObject, I linked the video in my post, the creator explains it way better than me.
Thanks for the response, I'll look into the drag and drop inspector thing.