Alternative to multiple inheritance

3

It is not possible to inherit from more than one C # class, so I came here for suggestions for my problem.

I'm building a little game using Unity. In Unity, the game objects ( GameObject ) inherit from a superclass called MonoBehaviour , as is the case with my Player class, and as is the case with my Enemy class.

Both Player and Enemy have the possibility to choose a target on the screen and execute Attack() . However, in the case of player , its target can be either Enemy or Player . In innocence I quickly created a Entidade class, put a RecebeAtaque(Attack a) method on it, and made Player and Enemy inherit from Entidade . After that, I made the method Attack get a Entidade parameter.

However, Player and Enemy already inherit from Monobehaviour , so this was not possible. I need them to inherit from MonoBehaviour , because this super class gives me ways to manipulate GameObject in the game scene.

How could I implement this?

    
asked by anonymous 16.05.2017 / 22:05

1 answer

2

Multiple inheritance is problematic and seldom needed indeed. How can one thing be two things at once? . Also, inheritance gain is very small in almost all scenarios, especially if you consider that composition should be preferred .

In general we just want to add behavior, this can be done with interface , especially when you can have code in the interface which gives C ++ , # and should have in C # 8 or languages that have < in> traits .

When the intention is to actually use more than one class in almost all situations it is possible to do this by the hierarchy, ie one class inherits from the other and it becomes available with the members of the two classes for other classes to inherit. It's all about understanding what the class means, what its role is, what it's all about in design.

In this example it seems that the solution is Entidade inherit from MonoBehavior .

Alternative

But I do not know what these classes do. I do not like the way these engines of games are architected. Is Enemy a MonoBehavior ? No, right? It's kind of weird. So should not have an inheritance there . Or you should do a composition so that Enemy has MonoBehavior or this should be just an interface to add behavior in the class you want.

And Entidade is what? It even seems to me that Enemy can be Entidade , but since I did not see the implementation of it, I do not know. It may have no function whatsoever or add nothing to the object, then a interface is more than adequate , yet more if it's just a marker , which may be the case.

    
17.05.2017 / 02:04