在C#

时间:2017-08-26 15:51:33

标签: c# class exception

因此,当按下某个键时,我需要将一个Labyrinth类的实例从Form1类传递给Player类,这样玩家就可以在没有碰撞的迷宫中移动。    首先我全局声明一个Labyrinth对象,这样当它在OnMouseClick函数中创建时,它将在类中的任何地方都可用,然后在OnKeyPress函数中我将它传递给Player类的实例并使用Move函数执行移动并检查碰撞。
   我得到"对象引用未设置为对象的实例"例外,我无法弄清楚它为什么不起作用。也许我在声明或实例化迷宫课时搞砸了,但我根本不知道另一种方法。有什么建议吗?

namespace Labyrinth
{
    public partial class Form1 : Form
    {
        Player player = new Player();
        Labyrinth labyrinth;

        private void OnMouseClick(object sender, MouseEventArgs e)
        {
            if (window=="lvlSelect")
                string clicked = levelMenu.Click(e);

            switch (clicked)
            {
                case "1":
                  level = 1; 
                  Labyrinth labyrinth = new Labyrinth(level);
                  break;
                case "2":
                  level = 2; 
                  Labyrinth labyrinth = new Labyrinth(level);
                  break;
                case "3":
                  level = 3; 
                  Labyrinth labyrinth = new Labyrinth(level);
                  break;
            }           
        }

        private void OnKeyPress(object sender, KeyPressEventArgs e)
        {
            char key = e.KeyChar;
            if (window == "game")
            {player.Move(k = key.ToString(), labyrinth)}
        }
    }
}

namespace Labyrinth
{
    class Player
    {
        int playerPosX;
        int playerPosY;
        public void Move(string key, Labyrinth labyrinth)
        {
            switch (key)
            {
                case "a":
                    if (!(playerPosX - 1 < 0) && 
                        (labyrinth.CheckCollision(playerPosX - 1, playerPosY)==false)) //I get the exception here
                        playerPosX--;
                    break;
                case ...
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

public partial class Form1 : Form
    {
        Player player = new Player();
        Labyrinth labyrinth = new Labyrinth(1); // you need to default it to 1 first instead of null. because you might key press then only mouse click

        private void OnMouseClick(object sender, MouseEventArgs e)
        {
         string clicked = "1"; /// default clicked to 1
            if (window=="lvlSelect") /// if selected level is diff, then change
                 clicked = levelMenu.Click(e);
        labyrinth = new Labyrinth(Convert.ToInt(level)); 
        }

        private void OnKeyPress(object sender, KeyPressEventArgs e)
        {
            char key = e.KeyChar;
            if (window == "game")
            {player.Move(k = key.ToString(), labyrinth)}
        }
    }