0

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

Dario Mazhara
  • 71
  • 1
  • 7
  • Seems like a reasonable suggestion. You need `mm` set to a valid _instance_ of `ManagerAndMovement`. It's not clear at all from your code where that instance should come from. Maybe when you create the `Collision` class you set that property to the containing object? – D Stanley Apr 22 '16 at 16:05

1 Answers1

0

Change Collision class constructor and pass ManagerAndMovement instance to it

public Collision(PictureBox n, ManagerAndMovement m)
{
    n = Collider; //seems wrong. it should be Collider = n
    mm = m;
}
Hamid Pourjam
  • 20,441
  • 9
  • 58
  • 74
  • You might also mention that `n = Collider;` accomplishes nothing. OP probably meant `Collider = n;` – piedar Apr 22 '16 at 16:15
  • I added that to the code (Shouldn't it be m = mm?). And the error is now in a different spot. I will update the code and showed more of the ManagerAndMovement class. T – Dario Mazhara Apr 28 '16 at 16:16