Hi everyone. I’m programming an rts and im having a problem with polymorphism
I have the parent class, Unit, and then it has a child, MobileUnit and finnaly two childs of MobileUnit, Attacker and Engineer.
I need the attacker to attack other units so i’ve createn this:
public override void ActionCallBack (T target)
{
base.ActionCallBack (target);
if (typeof(T) == typeof(Unit)) {
Unit attack = (Unit)Convert.ChangeType(target,typeof(Unit));
StartCoroutine(Attack(attack));
}
}
The problem is, when i send a unit to attack, for example an engineer, it gives this error:
InvalidCastException: Value is not a convertible object: Engineer To Unit
Please use code tags, it takes only a few seconds but saves everyone else much more time and greatly reduces the chance of confusion.
Also, why both with generics if you’re going to cast? Put a type constraint on it.
void ActionCallBack<T>(T target) where T : Unit
This way the compiler will let you access any of the public interfaces of the Unit type without having to cast, or just make it non generic and only accept Unit types and subtypes.
void ActionCallBack(Unit target)
what you currently have is really no better than this: