Attaching new script vs. MonoBehaviour inheritance

Hello !

I’m new to Unity and I must say, the community seems to be really good and active so I hope my newbie question won’t hurt anyone :slight_smile:

I’m developing a simple game with two teams. I need to easily compare team of each GameObject to know if they are enemies.

I was considering one of the two following methods :

  • Attach a script ‘TeamBehaviour’ to all my GameObject which are in a team. That way I can use GetComponent on my GameObject and call IsEnemy() in it.
  • Inherit my concrete class from ‘TeamBehaviour’ and call IsEnemy() in the concrete one.

Scripts are bugging me sometimes because they seems really close to inheritance (but I get the concept when you don’t have to add multiple scripts on one GameObject). So I was wondering when do you need to attach a new script to a GameObject and when you need to make the script atteched to your GameObject inherit from another one.

If you know exactly why or if you have another method, I would really appreciate it.

It’s fuzzy in my head, I hope it’s not in the post :slight_smile:

Thanks

1 Answer

1

A script component should encapsulate a single concept or responsibility and only inherit from another component when it extends on the base concept and needs to be able to be referenced by other objects as the base concept.

In your example, your way of thinking… is confusing me. Where do you need to compare if teams are enemies? In the TeamBehaviour script? Or do you have another component that needs to know if 2 TeamBehaviour instances are enemies? I don’t see why you would consider inheritance at all, you should be able to solve your problem by using a simple enum field to identify your teams. Or tagging the objects (though I would go with the enum field personally).

It's great, thank you for your help :)