I have two classes:
class Player
{
public string Id { set; get; }
public int yPos { set; get; }
public List<Shot> shots;
public Player(string _Id, int _yPos)
{
Id = _Id;
yPos = _yPos;
}
}
class Shot
{
public int yPos { set; get; }
public Shot(int _yPos)
{
yPos = _yPos;
}
}
When I try to put new Shot in list of shots for the player I get NullReferenceException:
Player pl = new Player("Nick",50);
pl.shots.Add(new Shot(pl.yPos)); // this line throws exception
Probably something ultimately simple.
In your Player constructor, just initialize shots = new List<Shot>();
You need to new the shots in the Player constructor (or before you add to it).
shots = new List<Shot>();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With