0

I am getting a null reference exception when I choose run in this snippet of code.

var monster = map[player.YPosition, player.XPosition].MonsterEncounter.Monster.MonsterName;
Console.WriteLine("You encounter a {0}.", monster);
var run = false;
while (map[player.YPosition, player.XPosition].MonsterEncounter.Monster.Health > 0 || !run)
     {
     Console.WriteLine("What your next move? Fight or Run?");
     var choice = Console.ReadLine().ToLower();
     switch (choice)
     {
         case "fight":
             Attack(player, map[player.YPosition, player.XPosition].MonsterEncounter.Monster);
             break;
         case "run":
             run = true;
             Movement(player, map[player.YPosition, player.XPosition]);
                                    break;
     }
}

And I know why, because when I run to a tile without a monster the while loop gets a null for its health. I cannot think of a way around this however. Can anyone help me?

Michael
  • 311
  • 4
  • 22
  • 1
    You can use an `if` statement and check whether certain variables exist before you try to use them. – Jashaszun Aug 18 '15 at 22:18
  • Assign the value of `map[player.YPosition, player.XPosition]` to a variable, then check if it's `null` before trying to access the `MonsterEncounter` member. Then reuse the variable in the rest of the code instead of repeating the `map[...]` part several times. – Lucas Trzesniewski Aug 18 '15 at 22:23

0 Answers0