Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Initiating jagged arrays by for loop.

Discussion in 'Scripting' started by Jujek, May 5, 2016.

  1. Jujek

    Jujek

    Joined:
    Oct 4, 2014
    Posts:
    6
    Greetings. Short question guys! Please read the comments in code.

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using System;
    4. using System.Collections.Generic;
    5.  
    6. public class MapScript : MonoBehaviour {
    7.  
    8.     public List<int>[][] Map;
    9.     void Awake () {
    10.         Map = new List<int>[60][];
    11.  
    12.         for(byte x = 0; x < 60 ; x++)
    13.         {
    14.             Map[x] = new List<int>[60];
    15.             // initialization of rows
    16.         }
    17. Map[23][34].Add(2) //trying to add int "2" to the int list located in the jagged array. Pops the NullReferenceException, as listed under the code
    18. print(Map[23][34]); // OUTCOME is "null" ; basically I think Im trying to print a regular list. Seems not though, as outcome for printing a regular list is
    19. //"System.Collections.Generic.List`1[System.Int32]"
    20. //That leads to a conclusion that something in the for loop is wrong?
    21. //However it's not like there is no "list" whatsoever, since if I try to print Map[23][34] without the "for" loop,
    22. //then there's an error, NullReference, same as Ive listed down there
    23. }
    24.  
    25. }
    After running the script exactly as it is:
    Error:"NullReferenceException: Object reference not set to an instance of an object"

    Ive done some research, but still I have no idea how I could fix it.
     
    Last edited: May 5, 2016
  2. jmjd

    jmjd

    Joined:
    Nov 14, 2012
    Posts:
    50
    Since you have a jagged array of Lists, remember you need to instantiate a list at every position in the array. To do this, you'll need an inner loop, inside your current for loop. Something like this:

    Code (CSharp):
    1.         for(byte x = 0; x < 60 ; x++)
    2.         {
    3.             Map[x] = new List<int>[60];
    4.             // initialization of rows
    5.  
    6.             for(int y = 0; y < 60; y++)
    7.                 Map[x][y] = new List<int>();
    8.         }
    9.