Problem with inherited classes in C#

Posted by Unniloct on Stack Overflow See other posts from Stack Overflow or by Unniloct
Published on 2010-04-23T22:14:43Z Indexed on 2010/04/23 22:23 UTC
Read the original article Hit count: 132

Filed under:
|
|

I have a class called "Entity," with two child classes: "Creature" and "Item." (I'm making a game.) Creature has two functions called "Attack," one for attacking Creatures, and one for attacking Items. So far, everything works well.

Now I'm working on the shooting bit, so I have a function called SelectTarget(). It takes all of the Entities (both Creatures and Items) in the player's view that the player can shoot and lets the player choose one.

So here lies the problem: SelectTarget() returns an Entity, but I need some code to figure out whether that Entity is a Creature or an Item, and process it appropriately.

Since this question looks kind of empty without any code, and I'm not 100% sure my explanation is good enough, here's where I'm at:

if (Input.Check(Key.Fire)) {
    Entity target = Game.State.SelectTarget.Run();
    this.Draw();
    if (target != null) {     
        //Player.Attack(target);
        // This won't work, because I have:
        //   Player.Attack((Creature)Target)
        //   Player.Attack((Item)Target)
        // but nothing for Entity, the parent class to Creature and Item.
        return true;
    }
}

(If the way the game is laid out seems weird, it's a roguelike.)

© Stack Overflow or respective owner

Related posts about c#

Related posts about class