I am making a small experiment game in Visual Studio (C#) I have a ManagerAndMovement class and a Collision class. The manager and movement class contains pictureboxes, which are in a list called walls, and i am trying to use that list in another class in a foreach loop to detect collision. Here's my code:
ManagerAndMovement class (attributes and constructer)
public List<PictureBox> walls;
public PictureBox wall;
Collision collision;
//Collider is a picturebox on the form, it is set to public
public ManagerAndMovement()
{
InitializeComponent();
collision = new Collision(Collider, this);
KeyDown += new KeyEventHandler(GameManager_KeyPress);
this.Controls.Add(PlayerTexture);
this.KeyDown += new KeyEventHandler(GameManager_KeyPress);
}
Whole collision class:
class Collision
{
PictureBox Collider;
ManagerAndMovement m;
public Collision(PictureBox n, ManagerAndMovement mm)
{
Collider = n;
m = mm;
}
public bool CheckForWall(String direct)
{
foreach (PictureBox wall in m.walls)
{
if (Collider.Bounds.IntersectsWith(m.wall.Bounds))
{
if (direct.Equals("left"))
m.xWall = wall.Location.X + wall.Width;
if (direct.Equals("right"))
m.xWall = wall.Location.X - wall.Width;
if (direct.Equals("up"))
m.xWall = wall.Location.Y + wall.Height;
if (direct.Equals("down"))
m.xWall = wall.Location.Y - wall.Height;
return false;
}
}
return true;
}
}
The error occurs in this line:
if (Collider.Bounds.IntersectsWith(m.wall.Bounds))
And the error is (pointing at the foreach loop and highlighting mm.walls):
Object reference not set to an instance of an object.
It also suggested this:
Use the "new" keyword to create an object instance