How to build gameobject heirarchies intelligently

Hi guys. I’m a newb to scripting and to Unity. Here’s my question.

I want to have two rpg monsters fighting each other, but there will be tons of species of monster. Most will have all of the same variables - health, attack power etc. In c++ (my home language) I would create a base class monster and derive particular monster classes from that for each species.

Should I do the same in Javascript? Does it work this way?

My idea was to

  1. Create BaseMonster.js GameObject with an exposed gameObject variable for a specific species GameObject, as well as exposed variables for all the base stats a monster needs.
  2. Write FireMonster.js as a specific monster class, with variables for mesh and animation etc.
  3. Attach FireMonster.js to a copy of BaseMonster.js to make a full fire monster, then turn that into a prefab for instantiation whenever I need it.

Or am I overthinking this? Should I simply make a seperate .js for each monster with no base ‘class’? What is more appropriate / more optimized?

Thank you for helping a newb out.

Base classes are great if you want to write routines that deal with all monsters in a single loop or with a specific function. You can create hierarchies in exactly the same way as you would in C++ except that you can only have single inheritance. The way around that is to use interfaces which are effectively contract definitions that if implemented guarantee that an object will perform certain functions, you can then cast suitable objects to the interface. The downside of interfaces is there is no implementation inheritance - just the definitions.

I’m surprised you are using JavaScript (or as some of us call it Unity Script) if you have a C++ background - C# is more similar to C++ and it is more obvious in its definitions of classes than JavaScript which hides the details.

Using inheritance in this way for your monsters is probably a bad idea IMO. It will by the end of your project bloat your base class (so all monsters are processing things they don’t have to be) or your sub-classes will become “monsters” themselves. Either way by the time you’re done with the project it will likely be a mess and difficult to maintain.

What I recommend is to have a base class for your monster which contains a way of specifying an array of attributes and each subclassed monster defines what this array of “attributes” are. e.g. each attribute is a enum + data and the monster base class simply processes this array. Think of attributes in this way as reusable components which can be kept simple and a monster is an array of these components.

This has the advantage of being fairly light-weight and doesn’t produce difficult to maintain code in the long run.