- Home /
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
Wait ... "Now I saw in an Unity example..."? Like, it was in a blog post on geocities, right after 10 reasons zombies are better than pirates?
What? It was an example from the Unity website. If that is what you mean.
Could you add a link to the example you saw in your question?
That's what I mean -- it was just some website. $$anonymous$$ost of the "random" stuff I see about Unity is either deliberate lies, or crack-pot opinions.
Gamasutra is running more Unity3d articles. Look in the comment sections for examples of internet wrongness. People say Unity can't do X, when a quick google leads to UnityDocs or UA and shows otherwise.
Answer by Sisso · May 18, 2014 at 07:41 PM
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 { }
Your answer
