Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 243
OwenAlexander Avatar asked Jan 31 '26 15:01

OwenAlexander


1 Answers

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;
     }
 }
like image 107
apxcode Avatar answered Feb 03 '26 04:02

apxcode