3
It is not possible to inherit more than one class in C#, so I come here looking for suggestions for my problem.
I am building a small game using Unity. In Unity the game objects (GameObject
) inherit from a superclass called MonoBehaviour
, as is the case in my class Player
, and as is the case with my class Enemy
.
So much Player
as Enemy
has the possibility to choose a target on the screen and run Attack()
. However, in the case of player
, your target may be both a Enemy
as much as another Player
. In innocence I quickly created a class Entidade
, I put in her a method RecebeAtaque(Attack a)
, and did Player
and Enemy
inherit from Entidade
. After that, I did the method Attack
receive a parameter Entidade
.
However, Player
and Enemy
already inherit from Monobehaviour
, thus, this was not possible. I need them to inherit from MonoBehaviour
, because this super class gives me ways to manipulate the GameObject
in the game scene.
How could I implement this?
Do
Entidade
inherit fromMonoBehavior
.– Maniero
Incredible as it may seem, this is exactly what I wanted. I tested the implementation here and it worked exactly as I expected. Thank you very much, it was such a simple thing, and I could not notice. If you want to post an answer, I mark as accepted :)
– Artur Trapp
While we cannot have multiple inheritance, we use interfaces to, for example, add behaviors to an object. In the case of Unity, the class
MonoBehavior
serves exactly that. You can compose a complex object with severalMonoBehavior
, I mean, you add behaviors. In fact, I try to avoid gigantic classes with many responsibilities, I suggest trying to break into smaller classes, respecting SOLID. In case, you already managed to solve the problem, just wanted to give more details ;) good luck!!!– Alisson