Witam. Dopiero zaczynam z obiektowym programowaniem i postanowiłem przećwiczyć to na prostej gierce konsolowej. Mam jednak problem z utworzeniem obiektu aby miał przyporządkowane startowe dane. Nie mam pojęcia jak mogę utworzyć ekwipunek z typu Item. Oto część kodu, który może powodować błędy :
...
name = Console.ReadLine();
Hunter myHunter = new Hunter(name, 1, 1, 1);
myHunter.DisplayStats();
...
class Hunter : Character
{
//Ctors
public Hunter() { }
public Hunter(string name)
: this(name, 1, 1, 1) { }
public Hunter(string name, int strength, int speed, int charisma)
: base(name, strength, speed, charisma) { }
//Methods
public override void DisplayStats()
{
ConsoleColor currentForeground = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.Blue;
Console.WriteLine("Oto dane na temat twojej postaci: ");
Console.WriteLine("Rodzaj postaci: Łowca");
base.DisplayStats();
Console.ForegroundColor = currentForeground;
}
public string CharName { get; set; }
public int CharStrength { get; set; }
public int CharSpeed { get; set; }
public int CharCharisma { get; set; }
public List<Item> Inventory { get; set; }
//Ctors
public Character() { }
public Character(string name)
: this(name,1,1,1)
{ }
public Character(string name, int strength, int speed, int charisma)
{
CharName = name;
CharStrength = strength;
CharSpeed = speed;
CharCharisma = charisma;
SetupData();
}
private void SetupData()
{
this.Inventory.Add(new Item { ItName = "zbroja", PlusStrength = 1, PlusSpeed = 0, PlusCharisma = 3 });
this.Inventory.Add(new Item { ItName = "buty", PlusStrength = 1, PlusSpeed = 0, PlusCharisma = 3 });
this.Inventory.Add(new Item { ItName = "hełm", PlusStrength = 1, PlusSpeed = 0, PlusCharisma = 3 });
}
...
public virtual void DisplayStats()
Trochę pokręciłem tutaj z konstruktorami ale ostatecznie ma się to odwoływać do kontruktora głównego w Character.cs.
Błąd, który mnie nęka:
System.NullReferenceException: Odwołanie do obiektu nie zostało ustawione na wystąpienie obiektu.
w FirstGameApp.Character.SetupData() w C:\Users\emils\source\repos\FirstGameApp\FirstGameApp\Character.cs:wiersz 53
w FirstGameApp.Character..ctor(String name, Int32 strength, Int32 speed, Int32 charisma) w C:\Users\emils\source\repos\FirstGameApp\FirstGameApp\Character.cs:wiersz 28
w FirstGameApp.Hunter..ctor(String name, Int32 strength, Int32 speed, Int32 charisma) w C:\Users\emils\source\repos\FirstGameApp\FirstGameApp\Hunter.cs:wiersz 18