I'm currently "newing" an instance of a class I have that derives from MonoBehaviour and store it in a list. The value of this instance is "null" however, even though it has all the fields of my derived class in it so it passes as null in null checks. After more reading it seems it's a bad idea to manually new up an instance of an object that derives from MonoBehaviour.

The class is an Actor class. I have a situation where enemy actors are 3D models in my scene and so I want them to derive from MonoBehaviour, but the player actors don't have world representations really. I just have a picture of them in the corner. Similar to Legend of Grimrock.

I wanted the 1 Actor class since the data they need is all the same and I wanted to avoid having 2 classes for no seemingly reason other than not newing up a MonoBehaviour derived class.

What are my options with this requirement when my player actors don't need MonoBehaviour but my enemy actors do but they all need to have the same properties?


1 Answer 1


You should be seeing a warning in the compiler log about newing a MonoBehavior directly. Always pay attention to the log.

MonoBehavior classes are really components and wont function without being attached to a GameObject instance.

GameObject object = new GameObject();
MyMonoBehavior mine = object.AddComponent<MyMonoBehavior>();
mine.specialValue = 42;

While it's difficult to be sure if this next part is relevant without seeing code samples, not everything has to be a MonoBehavior. MonoBehaviors give you a hook directly into the game loop. If what you have is meant to be data-only, and you don't need it to do calculations every frame, you can create normal classes and use them in other MonoBehaviors.

  • \$\begingroup\$ Yeah, I was thinking about not having it inherit from MonoBehaviours, but you can see my issue. Since monsters are 3D models in the scene it's easy enough to have it inherit and attach the script to the model, but because player characters aren't 3D models but just really 2D UI images they don't need to be attached to anything. Perhaps I need to make a choice and decide to either attach to the 2D ui elements for the players and have everything derive from Mono or don't derive from Mono and don't attach to enemies. \$\endgroup\$
    – user441521
    Jan 7, 2018 at 14:34
  • \$\begingroup\$ I think I'm going to create a proxy Actor class. ActorProxy will inherit from MonoBehavior and have an Actor property which that class doesn't. My plan is to create specific enemy scripts anyway that will derive from ActorProxy and those will fill out the Actor property in their Start() method. This way the no visuals players will just use Actor instances to represent them as they don't need to derive from MonoBehavior. \$\endgroup\$
    – user441521
    Jan 8, 2018 at 18:20

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .