Home > Enterprise >  InvalidCastException: Specified cast is not valid || Unity
InvalidCastException: Specified cast is not valid || Unity

Time:12-08

I got an error in Unity saying:
"InvalidCastException: Specified cast is not valid.
Tile.OnMouseDown () (at Assets/Tiles/Tile.cs:38)
UnityEngine.SendMouseEvents:DoSendMouseEvents(Int32)"

To be more precise, it complains about this line(38):
> if (OccupiedUnit.Faction == Faction.Hero) UnitManager.Instance.SetSelectedHero((BaseHero)OccupiedUnit);
I recently started learning Unity so I have no Idea how to fix that.
Attached the code below:

    if (OccupiedUnit != null)
    {
        if (OccupiedUnit.Faction == Faction.Hero) UnitManager.Instance.SetSelectedHero((BaseHero)OccupiedUnit);
        else
        {
            if(UnitManager.Instance.SelectedHero != null)
            {
                var enemy = (BaseEnemy)OccupiedUnit;
                Destroy(enemy.gameObject);
                UnitManager.Instance.SetSelectedHero(null);
            }
        }
    }
    else
    {
       if (UnitManager.Instance.SelectedHero != null)
        {
            SetUnit(UnitManager.Instance.SelectedHero);
            UnitManager.Instance.SetSelectedHero(null);
        }
    }

}

Thank you in advance.

CodePudding user response:

Accidently I found a way to fix that. For some reason explicit type cast in the form of SetSelectedHero((BaseHero)OccupiedUnit) didn't work but when I changed it to SetSelectedHero(OccupiedUnit as BaseHero) it started to work properly.
Don't know why it works this way but if someone has an idea I would be grateful if you could share your knowledge.

CodePudding user response:

GemuSenYou When you use SetSelectedHero((BaseHero)OccupiedUnit) and it fails, it will throw InvalidCastException, but with SetSelectedHero(OccupiedUnit as BaseHero), if it fails the result will be null, which you probably check somewhere in the code. That's my best quess :)

  • Related