Reputation: 103
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
Upvotes: 0
Views: 850
Reputation: 4595
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;
}
}
}
Upvotes: 5