0

So I’m trying to draw a grid to the screen with monogame using an array, but it keeps giving me the error “object reference must be set to instance of object”. I’ve initialized the grid as you can see, so I don’t know whats causing the problem. The exception is being thrown on the Globals.Spritebatch.draw line, and when I change the grid[i,j] to new Rectangle(), it works just fine, but I would prefer to use the grid. Here’s my code, any help/explanation of what I’m doing wrong would be appreciated.

public class Grid
    {
        Rectangle[,] grid;
        public Grid()
        {
        Rectangle[,] grid = new Rectangle[12, 8];
        for (int i = 0; i <= 11; i++)
        {
            for (int j = 0; j <= 7; j++)
            {
                grid[i, j] = new Rectangle(new Point(100 + 50 * i, 100 + 50 * j), new Point(50, 50));
            }
        }
    }
        public void Update()
        {
        }
        public void Draw()
        {
           for(int i = 0; i <= 11; i++)
            {
                for (int j = 0; j <= 7; j++)
                { 
                    Globals.spriteBatch.Draw(Globals.content.Load<Texture2D>("2d\\GridRect"), grid[i, j], Color.White);
                }
            }
        }
    }
  • Are you able to step into the code with a debugger and see what indexes for `i` and `j` are used when the error occurs? – Joe Sewell Jun 30 '20 at 20:22
  • 1
    The answer in the [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/q/4660142/1260204) is pretty much a "how to troubleshoot a NRE", a guidebook if you will. Use the advice in that answer to figure out what is causing the NRE in your code – Igor Jun 30 '20 at 20:22
  • @JoeSewell it stops at the first iteration (i =0, j = 0) – Sebastian Ehlke Jun 30 '20 at 20:29
  • 1
    The line ````Rectangle[,] grid = new Rectangle[12, 8];```` creates a new local variable named grid and initializes it. The rest of the method uses that local variable-not the field you want it to use. To fix this just replace it with ````grid = new Rectangle[12, 8];````. – Paramecium13 Jun 30 '20 at 20:46
  • @Paramecium13 oh my god. Duh. – Sebastian Ehlke Jun 30 '20 at 20:52

0 Answers0