I've currently only been learning C# for a week so apologies for any stupid errors but I'm trying to call a method within a switch statement to take away an integer value that is declared within a list from the argument given to the method, the argument in this case is the health of the currEnemy object, but when the currEnemy.health value is printed out to the console it's value is unchanged and I can't figure out why.
The list that stores the integer value that the currEnemy.health is taken away by a long with the health variable which is set to an integer value in the Enemy class:
public List<Weapon> myWepList = new List<Weapon>(){
new Weapon {name = "Dagger", dmg = 10, stamDrain = 5},
new Weapon {name = "Sword", dmg = 20, stamDrain = 20},
new Weapon {name = "Halberd", dmg = 40, stamDrain = 20}
};
public int health{ get; set; }
The method within the player class that should take away the 'dmg' value from the enemy.health value and set enemy.health to a new value:
public void charAttack(int enemyHealth)
{
enemyHealth -= equippedWep[0].dmg;
}
Then the code that calls the above method to display the currEnemy.health's new value:
enum PlayerInput
{
Attack,
Block,
}
while (gameStart == true) //this part onwards is stored in the main method
{
string playerInput = Console.ReadLine().ToUpper();
PlayerInput inputChoice;
Console.WriteLine("Type 'attack' to attack the enemy");
if (Enum.TryParse<PlayerInput>(playerInput, true, out inputChoice))
{
switch (inputChoice)
{
case PlayerInput.Attack:
currPlayer.charAttack(currEnemy.health);
Console.WriteLine("Enemy Health is {0}", currEnemy.health);
break;
default:
break;
}
}
}
I'd also appreciate if any general advice is just given to me about my code considering I'm completely new to C# so any constructive advice would be great, thank you.
This method:
public void charAttack(int enemyHealth)
{
enemyHealth -= equippedWep[0].dmg;
}
... is basically pointless. The statement enemyHealth -= ...
only affects the parameter called enemyHealth
. It won't change currEnemy.Health
at all - because the method argument is passed by value. In other words, the process is:
currEnemy.health
is evaluatedenemyHealth
enemyHealth
isn't used at allSee my article on parameter passing for more details.
There are various ways you could tackle this - for example, you might want:
currPlayer.Attack(currEnemy);
where the Attack
method would look something like:
public void Attack(Enemy enemy)
{
Weapon weapon = equippedWep[0];
enemy.Health -= weapon.Damage;
}
Note that the last line is very different to your previous code, because it would set the value of enemy.Health
afterwards... you wouldn't just be changing a parameter, but the state of an object.
See more on this question at Stackoverflow