- Home /
Polymorphism trouble: can't cast child to parent
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> (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
Thanks.
Check here: https://msdn.microsoft.com/en-us/library/dtb69x08%28v=vs.110%29.aspx Perhaps you might be passing a null?
To use Convert.ChangeType your object should implement IConvertible. https://msdn.microsoft.com/en-us/library/dtb69x08(v=vs.110).aspx
However you shouldn't need to cast a child to a parent, the child is already that class. Try
public override void ActionCallBack(Unit target)
{
StartCoroutine(Attack(target));
}
maccabe i can't do that because im using type T and i need to convert it to unit.
Answer by FlyPT · Jul 18, 2015 at 05:19 PM
If anyone is having this problem too, i've fixed it,
public override void ActionCallBack<T> (T target)
{
base.ActionCallBack (target);
if (typeof(T) == typeof(Unit)) {
Unit attack = target as Unit;
StartCoroutine(Attack(attack));
}
}
I removed the Convert.ChangeType and now it works perfectly. Thanks everyone for trying to help.