I’m not able to find any good explanation on this and having trouble to decide.
Should you prefer to use components instead of interfaces in unity?
Example.
I have a GameObject with a script Unit which derives from: IHealth, IMovement etc. Why should I use a component Health and another component Movement and add it to Unit? I can just use “GetComponent().DoDamage()” instead of “GetComponent().DoDamage()”
Are there any major benefits with using components instead of interface? Or have I misunderstood the whole idea of it all?
I’ll only give you my investigation so far, but what I’m finding is both have their benefits, and sometimes it’s good to use both in tandem. Components are excellent as they don’t force every instance of a class to subscribe to an interface, however it can be nice when you know something will always have ‘a thing’ that does ‘something’. Like for example you can have a IDamageable interface, and that means anything with that interface can lets say ‘TakeDamage(float amount)’. A Health component wouldn’t have the flexibility of deciding what TakeDamage(float amount)’ would do, however an interface can have any implementation of this method. I mean you can just give the Health component a public event and let other components subscribe to it as they want. De-coupling the result of the action from the trigger. I mean you have many many many options in Unity, and there isn’t a single set way. I’ve seen beautiful systems using either or both. I tend to use components with Interfaces. That way it’s easy to refactor changes in my code, but that’s just my habits.
Sometimes all these options make it hard not to choose “wrong path” and end up with unreadable code with loads of bugs ^^
My current approach is to have separate components. For an example “Health” which will derive from IDamagable interface. Therefore if I can have a tree or character or stone etc. that all can take damage and apply the damage differently. Stone might have a component Durability which derives from IDamagable. Therefore each will have a maxhealth, health and functions TakeDamage and maybe Heal.