So this is a "game" using forms for now. But I am getting an error with my object and I'm not sure exactly why I am. I have 2 classes below : Player & Weapon. I'm trying to get the result of player.Attack() to show as a string, but when I click the button on the form to do so, it gives me the lovely "object reference not set to an instance of an object" error. I've tried Convert.ToString(player.Attack()); also tried String.Format(player.Attack()), even set a string variable to take the conversion to a string, but i keep getting this error. I just want the result of the method to show as a string on my form's label.
This is the PLAYER class
public class Player
{
private Form1 Login { get; set; }
private Weapon sword;
public string PlayerName { get; set; }
public int Health { get; set; } = 36;
public int Strength { get; set; } = 6;
public Player(string playername, int health, int strength, Weapon s)
{
this.Login.UserName = playername; //gets character name from form1 and makes it the username throughout the game.
// this.PlayerName = playername;
this.Health = health;
this.Strength = strength;
this.sword = s;
}
public int Attack()
{
return sword.Attack(this.Strength);
}
This is the WEAPON class
public class Weapon
{
public string Name { get; set; } = "Hel Fire";
public int AtkDmg { get; set; } = 4;
public Weapon(string name, int attack)
{
this.Name = name;
this.AtkDmg = attack;
}
//Attack function that will take users STR and Sword Strength
public int Attack(int strength)
{
int result = strength + this.AtkDmg; // AtkDmg is the weapons Strength
return result;
}
This is the forms where the button_click object is.
private void AtkSword_Click(object sender, EventArgs e)
{
int GoblinHealth = 36;
int GoblinAttack = 2;
if (GoblinHealth != 0)
{
GoblinHealth -= player.Attack();
player.Health -= GoblinAttack;
}
//below should display text and results from attack
ResultsLabel.Text = Format.ToString("{0} Attacks the goblin. The goblin is at {1} HP. \n {2} is at {3} HP", player.PlayerName, GoblinHealth, player.PlayerName, player.Health);
}