Search code examples
c#inheritanceunity-game-engineinstancesgameobject

How to create instances of a base character class


In order for a class to be attached to a GameObject it needs to inherit from MonoBehaviour. If I create a base character class that contains all the attributes shared by both NPCs and PCs, how do I create instances of that class and attach it to game objects? To give a concrete example of the problem, if the base character class has variables like health, stamina, strength etc, and I want a particular game object to have a particular set of those attributes, how do I attach that to a game object as it cannot inherit the base character class?

I suspect the mistake I'm making is to think that these instances need to even be attached to the objects that I want them to be associated with, but some clear guidance here would be most appreciated.


Solution

  • It seems that what you really want is a base class that also allows its children to be MonoBehaviours. You can accomplish this by making your base class an abstract MonoBehaviour and inheriting from it.

     public abstract class Base : MonoBehaviour
     {
         protected int HP;
     }
    

    Then your children of this class will also be MonoBehaviours which you can attach to GameObjects.

     public class Ninja : Base
     {
         void Start()
         {
              HP = 100;
         }
     }