OOP beginner here and my problem is when i get to this event :
private void button1_Click(object sender, EventArgs e)
{
progressBar2.Increment(-25);
splitContainer1.Panel1.Enabled = false;
Thread.Sleep(2100);
int preAttack = myCurrentOpponent.SetAttack();
oppAttack = myCurrentOpponent.Attack(preAttack);
progressBar1.Increment(oppAttack.dommage);
textBox1.Text += myCurrentOpponent.Name + "Used " + oppAttack.AttackName;
}
I get an error : Object reference not set to an instance of an object.
Things you need to know myCurrentOpponent is an object chosen randomly in a collection of 3 monsters type. I’ll use Gollum for this example wich is one of the 3 types. Gollum inherit from Monster and overrides Name, Level, Health, PreAttack and SetAttack from is base.
public abstract class Monster
{
public abstract string Name { get; }
public abstract int Lv { get; }
public abstract int Hp { get; }
public abstract int SetAttack();
public abstract Attack Attack(int x);
public Monster()
{
}
}
Nothing in here is set because of this :
public class Gollum : Monster
{
Attack[] myAttack = new Attack[4];
public override string Name
{
get
{
return "Gollum";
}
}
public override int Hp
{
get
{
return 100;
}
}
public override int Lv
{
get
{
return 3;
}
}
public override int SetAttack()
{
Random randnum = new Random();
int x = randnum.Next(5);
myAttack[0].AttackName = "Charge";
myAttack[0].dommage = -10;
myAttack[1].AttackName = "Scratch";
myAttack[1].dommage = -12;
myAttack[2].AttackName = "Throw Rock";
myAttack[2].dommage = -15;
myAttack[3].AttackName = "Strangle";
myAttack[3].dommage = -16;
return x;
}
public override Attack Attack(int x)
{
return myAttack[x];
}
public Gollum()
{
}
Everything is set in the 3 monster sub-classes. Now, let’s say the chosen monster is Gollum and I click button 1, as soon as the compiler reaches this line…
myAttack[0].AttackName = "Charge";
… called from this line…
int preAttack = myCurrentOpponent.SetAttack();
…I get the error.
Am i missing a constructor for my Gollum Class ? And if I am how can i code it
since everything is set directly in the property.
I really hope someone can help me on this on because I really don’t know where to look.
Hope this is clear enough and don’t hesitate to ask if you need more code lines.
Thanks in advance
You haven’t filled the arrat
myAttackwith any objects. When you initialize the array, it is created withnullreferences. You need to add these lines before the line you get the error on:This initializes each array entry with a new
Attackobject so that you can now set properties on them.