Two Monobehaciour In One .cs File

Hello, is it possible create two behaviours in one .cs file ? Thanks for help!

You can create more than one class or struct in a file but it is not advised because it’s hard to maintain.

I don’t think you can do it with monobehaviours though, but you can very easily check in the editor.

1 Like

You can, but you can’t attach the second MonoBehaviour to any gameobject in the editor. This is because the thing that’s attached to the GameObject (inside the scene file) is the script file, not the class inside it. So if you have several MonoBehaviours in the file, it won’t know which one to pick.

We do this if a script needs to attach a MonoBehaviour to some object to achieve something, but that MonoBehaviour isn’t supposed to be added at any other point So it’s uncommon, but not unheard of.

4 Likes

To be more exact: Unity requires to have MonoBehaviours (actually I think it even applies to all classes deriving from UnityEngine.Object) in a file with the exact same name as the class.

1 Like