0

I am shaking off my programming rust and screwing around with unity but I am running into a NullReferenceException during my initialization.

I have a 2d array of integers in a class see the snippet below

public class Map : MonoBehaviour 
{
     int[,] Tile;
     int sizeX;
     int sizeY;
     void Start()
     {

          for (int posX = 0; posX != sizeX; posX++)
          {
               for (int posY = 0; posY != sizeY; posY++)
               {
                    Tile[posX, posY] = new int() 0;

               }
          }
     }
 }

the line

Tile[posX,posY] = new int() 0;

keeps throwing null reference, I have tried to initialize it a number of ways and changed my structure to use int containers instead of game objects as i had intended yet I still run into this error.

All my research tells me I need to initialize but in my mind I am! Where have i gone wrong? Apologize in advance if I missed something in my search queries or am wasting anyone's time by posting this question.

Thank You

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
DevSol
  • 3
  • 1
  • 1
    You didn't initialize Tile: `int[,] Tile = new int[sizeX, sizeY];` When, you do, it will contain all 0's, so the loop is not necessary. Also, `new int() 0;` is not valid code – Dennis_E Aug 02 '16 at 13:37
  • Want to thank you for responding so quickly. I feel like i tried this exact same thing last night to no avail! Yet i try it today and exactly what you said worked. Thanks so much. – DevSol Aug 02 '16 at 13:42

1 Answers1

1

Well, you get this error, because your Array is not initialized.

You are missing something like Tile = new int[sizeX, sizeY];

Besides that, using Tile[x,y] = some int you are initializing the arrays fields.

(Btw is new int() 0 some fancy syntax I haven't heared about?)

nyro_0
  • 1,135
  • 1
  • 7
  • 9