0

I've got a function where I assign variables based on who is the initiator.

function is like this if it's the characters turn to attack Attack(true)

goes to this function

    function Attack(bool CharacterAttacking){    
        var Attacker = Monster;
        var Target = Character;

        if (CharacterAttacking)
        {
            Attacker = Character;
            Target = Monster;
        }

monster is selected by default.

but if I want to switch it around so that the character is the attacker in my if, then I get the error

Cannot implicitly convert type Game.Models.Monster to Game.Models.Character

How can I switch it around so that the attacker becomes the character and the target becomes the monster?

Thank you

Petter Petter
  • 93
  • 1
  • 8
  • 1
    Use an `Interface` and make sure both the Games.Models.Monster class and the Games.Models.Character class implement that interface. Any common functionality will be declared on the interface. Then they can be used interchangeably. – Dmitriy Khaykin Jun 09 '16 at 00:36

1 Answers1

5

In this situation you would need to implement an interface or base class. This allows multiple class types to be housed in the same object type as long as they implement that interface or derive from the base class.

public interface IFighter
{
    void Attack();
    void Defend();
}

Then you would have to implement this interface in your Character and Monster classes.

public class Monster : IFighter
{
    public void Attack()
    {
        //some attack logic
    }

    public void Defend()
    {
        //some defense logic
    }
}

public class Character : IFighter
{
    public void Attack()
    {
        //some attack logic
    }

    public void Defend()
    {
        //some defense logic
    }
}

Once you have this setup you can add these properties to your class that is holding the battle information. Then you can implement the method you are trying to.

public class Battle
{
    public IFighter Attacker = Monster;
    public IFighter Target = Character;

    public void Attack(bool characterAttacking)
    {
        if (characterAttacking)
        {
            Attacker = Character;
            Target = Monster;
        }
    }
}
Matt Rowland
  • 4,575
  • 4
  • 25
  • 34