所以这是一个"游戏";目前正在使用表单。但是我的对象出现了一个错误,我不确定我为什么会这样;武器我正在努力取得球员的成绩。攻击((以字符串形式显示,但当我点击表单上的按钮时,它会给我一个可爱的"对象引用未设置为对象的实例";错误我尝试过Convert.ToString(player.Attack(((;还尝试了String.Format(player.Attack(((,甚至设置了一个字符串变量来转换为字符串,但我一直收到这个错误。我只想将方法的结果显示为表单标签上的字符串。
这是PLAYER级
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);
}
这是武器级
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;
}
这是button_click对象所在的窗体。
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);
}
我认为问题出在这里:
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);
您正在设置变量this.Login.UserName,而不是Player.Playername。稍后您尝试访问它,但它不存在。您应该设置:
public Player(string playername, int health, int strength, Weapon s)
{
this.Playername = playername //here
this.Health = health;
this.Strength = strength;
this.sword = s;
}
或使用登录用户名
ResultsLabel.Text = Format.ToString("{0} Attacks the goblin. The goblin is at {1} HP. n {2} is at {3} HP", this.Login.UserName, GoblinHealth, this.Login.UserName, player.Health);