Foreach循环不在单独的类

时间:2016-04-22 16:03:43

标签: c# .net nullreferenceexception

我正在Visual Studio中制作一个小型实验游戏(C#) 我有一个ManagerAndMovement类和一个Collision类。管理器和移动类包含图片框,它们位于名为wall的列表中,我试图在foreach循环中的另一个类中使用该列表来检测碰撞。 这是我的代码:

ManagerAndMovement类(属性和构造函数)

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);

    }

整个碰撞类:

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;

    }

}

此行发生错误:

if (Collider.Bounds.IntersectsWith(m.wall.Bounds))

错误是(指向foreach循环并突出显示mm.walls):

  

对象引用未设置为对象的实例。

它还暗示了这一点:

  

使用“new”关键字创建对象实例

1 个答案:

答案 0 :(得分:0)

更改Collision类构造函数并将ManagerAndMovement实例传递给它

public Collision(PictureBox n, ManagerAndMovement m)
{
    n = Collider; //seems wrong. it should be Collider = n
    mm = m;
}