I try to refer to an array in the Game1 class by creating an object of the Game1 class with its definition Game1 gameObject; , its declaration gameObject = new Game1(); in the constructor, and its usage gameObject.tileArray[xInt, yInt].treed = true;.
The game1 class itself remains unchanged in its class code other than some methods and variables. When I try to use this code in the TreeRegion class it gives me “Object reference not set to an instance of an object,” leading me to believe that the game1 class is null somehow.
How might one change the class or object in order to refer to game1’s variables? Mind you I am self-taught and still rather new to C#.
The class that refers to game1:
http://pastebin.com/0chEcKfq
Game1 itself
http://pastebin.com/zLDVzCca
Not necessary. Look at your expression:
That will throw a
NullReferenceExceptionif any of these are true:gameObjectis null (unlikely, given the code you’ve shown)gameObject.tileArrayis nullgameObject.tileArray[xInt, yInt]is nullYou haven’t shown us the
Game1class – it seems very likely that either the second or third bullet is the problem here.You should probably consider whether this should actually be part of the
Game1API rather than digging down the level like this:… or whatever the better name might be. It certainly looks like you’re missing some encapsulation here.
(Personally I wouldn’t really recommend learning C# via something like XNA. I think while you’re still at the stage of learning the language and core libraries, it’s a better idea to work in a simple environment such as console applications. I realize they may seem boring, but a bit of groundwork up-front may make a huge different in the long run.)
EDIT: Now we can see
Game1(which could do with a new name – and you should try to follow the .NET naming conventions) I strongly suspect thatcreateTilesis causing the problem. It’s not at all obvious that that will actually populate every element oftileArray– particularly as you never even useaorb. My guess is thatgameObject.tileArray[xInt, yInt]is returningnullin yourTreeRegioncode.EDIT: Looking at how you’re creating the array, it’s even more concerning:
Did you really want a 10000×10000 array? Are you sure you need this
gridScope? I would have expected:Note that in
createTilesyou’re only populating at mostgridHeight * gridWidthelements (i.e. ten thousand out of the ten million elements in the array).