6 Replies - 5310 Views - Last Post: 07 July 2012 - 11:17 AM Rate Topic: -----

#1 cgseif323  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 27
  • Joined: 01-April 09

NullReferenceException (And yes, I've searched this forum)

Posted 06 July 2012 - 08:00 PM

Hello,
I'm a novice C# programmer, trying to code this text-based game. I've been pulling my hair out about this error:

NullReferenceException was unhandled - Object reference not set to an instance of an object.

Yes, of course I tried to Google this problem and I even searched DIC, but I still can't figure it out. Here's some code (error is at line 29):

GameManager.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TextRPGv2;

namespace TextRPGv2
{
    static class GameManager
    {
        // Public Methods
        public static void ShowTitleScreen()
        {
            Console.Clear();
            Console.WriteLine();
            Console.WriteLine(TextUtils.WordWrap("*** Text RPG ***\n A simple RPG by Chris Seifried.\n\n\n",
                Console.WindowWidth));
            Console.WriteLine("\nNOTE: You may type 'help' at any time to see a list of commands.");
            Console.WriteLine("\nPress a key to begin.");

            Console.CursorVisible = false;
            Console.ReadKey();
            Console.CursorVisible = true;
            Console.Clear();
        }

        public static void StartGame()
        {
            Player.GetCurrentLocation().Describe(); // TODO: Keep getting an exception here
            TextBuffer.Display();
        }

        public static void EndGame(string endingText)
        {
            Program.quit = true;

            Console.Clear();

            Console.WriteLine(TextUtils.WordWrap(endingText, Console.WindowWidth));
            Console.WriteLine("\nYou may now close this window.");
            Console.CursorVisible = false;

            while (true)
                Console.ReadKey(true);
        }

        public static void ApplyRules()
        {

        }
    }
}



Definition of GetCurrentLocation()
        public static Location GetCurrentLocation()
        {
            return TextRPGv2.Level.Locations[posX, posY];
        }



Definition of Describe()
        public void Describe()
        {
            TextBuffer.Add(this.description);
            TextBuffer.Add(this.GetItemList());
            TextBuffer.Add(this.GetExitList());
        }



I don't understand this error because I don't have any variables that are null. The Autos and Locals windows are blank, so I guess we can rule the null thing out. This must be a class issue I assume. But how? I can't make an instance of the Player class because it's static anyways.

If you need any more code, I'll certainly put it up. This is probably a simple issue, but I just can't figure it out.
Please help, and thank you!

Chris

This post has been edited by cgseif323: 06 July 2012 - 08:02 PM


Is This A Good Question/Topic? 0
  • +

Replies To: NullReferenceException (And yes, I've searched this forum)

#2 modi123_1  Icon User is online

  • Suitor #2
  • member icon



Reputation: 9196
  • View blog
  • Posts: 34,538
  • Joined: 12-June 08

Re: NullReferenceException (And yes, I've searched this forum)

Posted 06 July 2012 - 09:59 PM

Try putting a break point on line 29 and seeing what the object "Player" is. I don't see it declared so my guess that is your problem... but you should verify.

Debugging
Was This Post Helpful? 0
  • +
  • -

#3 Mobuis1995  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 42
  • Joined: 15-February 12

Re: NullReferenceException (And yes, I've searched this forum)

Posted 06 July 2012 - 10:20 PM

In start game, where you say
 Player.GetCurrentLocation().Describe(); 
aren't GetCurrentLocation() and Describe() their own methods? Also, it's always helpful to step through the code.
Was This Post Helpful? 0
  • +
  • -

#4 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 6063
  • View blog
  • Posts: 23,515
  • Joined: 23-August 08

Re: NullReferenceException (And yes, I've searched this forum)

Posted 07 July 2012 - 02:47 AM

What Does This Error Mean?
Was This Post Helpful? 0
  • +
  • -

#5 cgseif323  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 27
  • Joined: 01-April 09

Re: NullReferenceException (And yes, I've searched this forum)

Posted 07 July 2012 - 10:22 AM

View Postmodi123_1, on 06 July 2012 - 10:59 PM, said:

Try putting a break point on line 29 and seeing what the object "Player" is. I don't see it declared so my guess that is your problem... but you should verify.

Debugging


I declared the Player class in a separate file, because it's pretty large. Should I post it?


View PostMobuis1995, on 06 July 2012 - 11:20 PM, said:

In start game, where you say
 Player.GetCurrentLocation().Describe(); 
aren't GetCurrentLocation() and Describe() their own methods? Also, it's always helpful to step through the code.


Yes, GetCurrentLocation() is a method in the Player class, and Describe() is in the Location class.
I tried stepping through it, and the code went through the GetCurrentLocation() method, so this must be a problem with how Describe() is called/is set up. But I don't understand how that could throw a NullReferenceException?

Also, thanks for replying!
Was This Post Helpful? 0
  • +
  • -

#6 Skydiver  Icon User is offline

  • Code herder
  • member icon

Reputation: 3572
  • View blog
  • Posts: 11,106
  • Joined: 05-May 12

Re: NullReferenceException (And yes, I've searched this forum)

Posted 07 July 2012 - 10:50 AM

If you made it as far as Describe():
public void Describe()
{
    TextBuffer.Add(this.description);
    TextBuffer.Add(this.GetItemList());
    TextBuffer.Add(this.GetExitList());
}



Step through the code to be certain. TextBuffer could be null. If TextBuffer.Add() dereferences it's parameters, description could be null. Or the return values of GetItemList() or GetExitList() could be null.

If you don't make it into Describe() that means that the actual array entry at Locations[posX, posY] is null.

Without posting all the relevant parts of your code, we can only make guesses and trying to guide you in the debugging process.

This post has been edited by Skydiver: 07 July 2012 - 10:51 AM

Was This Post Helpful? 0
  • +
  • -

#7 cgseif323  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 27
  • Joined: 01-April 09

Re: NullReferenceException (And yes, I've searched this forum)

Posted 07 July 2012 - 11:17 AM

Alright, I finally got something. I kept stepping through the code, and I stopped on what GetCurrentLocation() returns. It now says in the Autos window that Level.Locations[1,2] is null, Level.Locations[0,0] is null, and Level.Locations[0,1] is null. I stepped through everything a dozen times, and I didn't see this before. Anyways, here's the Level class...

Level.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TextRPGv2;

namespace TextRPGv2
{
    static class Level
    {
        private static Location[,] locations;

        #region Properties

        public static Location[,] Locations
        {
            get { return locations; }
        }

        #endregion

        public static void Initialize()
        {
            BuildLevel();
        }

        private static void BuildLevel()
        {
            locations = new Location[1, 2];

            LocationDB locationDB = new LocationDB();

            Player.PosX = 0;
            Player.PosY = 0;
        }
    }
}



Location.cs
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using TextRPGv2;

namespace TextRPGv2
{
    /// <summary>
    /// This is the base class for every location
    /// in the game.  Add more fields if necessary.
    /// </summary>
   
    class Location
    {
        private string title;
        private string description;

        private List<string> exits;
        private List<Item> items;

        #region Properties

        // not relevant

        #endregion

        public Location()
        {
            exits = new List<string>();
            items = new List<Item>();
        }


        // Public Methods

        #region Public Methods

        public void Describe()
        {
            TextBuffer.Add(this.description);
            TextBuffer.Add(this.GetItemList());
            TextBuffer.Add(this.GetExitList());
        }

        public void ShowTitle()
        {
            TextBuffer.Add(this.title);
        }

        public Item GetItem(string itemName)
        {
            foreach (Item item in this.items)
            {
                if (item.Name.ToLower() == itemName.ToLower())
                    return item;
            }
            return null;
        }

        public void AddExit(string direction)
        {
            if (this.exits.IndexOf(direction) == -1)
                this.exits.Add(direction);
        }

        public void RemoveExit(string direction)
        {
            if (this.exits.IndexOf(direction) != -1)
                this.exits.Remove(direction);
        }

        public bool CanExit(string direction)
        {
            foreach (string validExit in this.exits)
            {
                if (direction == validExit)
                    return true;
            }
            return false;
        }

        #endregion

        // Private Methods

        #region Private Methods

        private string GetItemList()
        {
            string itemString = "";
            string message = "Items in Room:";
            string underline = "";
            underline.PadLeft(message.Length, '-');

            if (this.items.Count > 0)
            {
                foreach (Item item in this.items)
                {
                    itemString += "\n[" + item.Name + "]";
                }
            }

            else
            {
                itemString = "\n<none>";
            }

            return "\n" + message + "\n" + underline + itemString;

        }

        private string GetExitList()
        {
            string exitString = "";
            string message = "Possible Directions:";
            string underline = "";
            underline.PadLeft(message.Length, '-');

            if (this.exits.Count > 0)
            {
                foreach (string exitDirection in this.exits)
                {
                    exitString += "\n[" + exitDirection + "]";
                }
            }

            else
            {
                exitString = "\n<none>";
            }

            return "\n" + message + "\n" + underline + exitString;
        }

        private string GetCoordinates()
        {
            for (int y = 0; y < Level.Locations.GetLength(1); y++)
            {
                for (int x = 0; x < Level.Locations.GetLength(0); x++)
                {
                    if (this == Level.Locations[x, y])
                        return "[" + x.ToString() + "," + y.ToString() + "]";
                }
            }

            return "This location is not within the Locations grid.";
        }

        #endregion
       
    }
}



LocationDB.cs - Sets the properties of each town/other location in the game
using System;
using TextRPGv2;
using System.IO;

namespace TextRPGv2
{
    class LocationDB
    {
       public Location Glenshaw()
        {
            Location location;
            Item item;

           //////////////////////////////////////////////////////////
           // Glenshaw

           location = new Location();

           // Assign it to a location 0, 0
           Level.Locations[0, 0] = location;

           location.Title = "Glenshaw";
           location.Description = "You are in your home town.";

           location.AddExit(Direction.South);

           return Glenshaw();
        }

        public Location Etna()
       {
           Location location;
           Item item;

           //////////////////////////////////////////////////////////
           // Etna

           location = new Location();

           // Assign it to a location 0, 1
           Level.Locations[0, 1] = location;

           location.Title = "Etna";
           location.Description = "You have entered Etna - A congested, rundown town that is very close to Glenshaw.";

           location.AddExit(Direction.North);

           return Etna();
       }
    }

}



I've looked over every resource that was linked to by others, and they were helpful. At least we narrowed down the issue -.-

Thanks!
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1