Good inheritance practice in Unity?

Hi

I’ve been using a style like this:

abstract class Character : MonoBehaviour { }

class Enemy : Character { }
class Player : Character { }

Now I saw in an Unity example that they do not inherit the MonoBehaviour part, but separate it. Like this:

abstract class Character { }
class Enemy : Character { }
class Player : Character { }

class EnemyBehaviour : MonoBehaviour { }
class PlayerBehaviour : MonoBehaviour { }

In hindsight the second case seems more fitting. But I don’t know how to correctly implement a class into the behaviour while keeping it scale- and maintainable.

What is the correct practice when using the second case?

V1ncam

There is never a real “correct way” of do things, what exist is trade offs. Its all depending of context. In your example, I prefer the simple one, but I could use the second one if a is multiplayer game because I can create instance without a GameObject and are easy to serialize.

If you don’t see any benefit in the change, don’t change, or try to experiments both implementations to see.

You can have something like it:

class Character : MonoBehaviour { }
class EnemyBehaviour : MonoBehaviour { }
class PlayerBehaviour : MonoBehaviour { }

Personally I like a more component by functionality:

// playe or enemy
class HasTeam  : MonoBehaviour { }
// can be target or destroyed
class Damageable  : MonoBehaviour { }
// can be contorled by player
class Controllable : MonoBehaviour { }