1
\$\begingroup\$

I wanted to incorporate changing location in an rpg, so I began by creating a class Location and assign every Location to a multi-dimensonal array, like so:

WorldMap[0, 0] = new Location("Majula");

I created two int variables named LocationY and LocationX set to the starting location. Now I got a command handler, when I type "Move South", I update the position with this dead simple code:

LocationY++;

Mind you, this is just for testing purposes, I just like to break a game into many small components that gets added as I get, or know better.

Now when I want to get my current location, I call it like this:

Console.WriteLine("He then headed south, until he arrived at {0}", WorldMap[PlayerLocationY, PlayerLocationX].Name);

That's cool and all, and it works, but I don't like typing too much if I can avoid it, so I wanted to change the call of WorldMap[PlayerLocationY, PlayerLocationX].Name to something more readable like currentLocation.Name.

So I tried this bit of code:

Location currentLocation = WorldMap[PlayerLocationY, PlayerLocationX];

Obviously, I get a NullReferenceException... I'm completely clueless, and I'm sure I'll probably say to myself "duh" when I'll get an answer.

And yeah, still learning, Console still rocks my socks!

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

It looks like you want a C# Property with a getter:

Location currentLocation
{
   get 
   {
       return WorldMap[PlayerLocationY, PlayerLocationX]; 
   }
}

Put this in the body of your class, along with the declarations for member variables like WorldMap and the player's coordinates. You can add an access modifier if you want it to be public or protected.

Now when you write something like currentLocation.Name, it will call this get function internally, return the requested value from the WorldMap, and then dig out the Name of that returned location.

(Note: this will still give you a NullReferenceException if either your WorldMap is undefined or lacks an entry at this X,Y coordinate - so make sure your data is properly initialized!)

\$\endgroup\$
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .