- Home /
How to Instantiate an Integer Array in an Array of Arrays?
I tried to create an array of arrays in Unity in order to edit the values in the Inspector, as you can't simply edit a multidimensional array. I want to be able to input an X and Y value that will allow me to adjust the length and width of the arrays.
[System.Serializable]
[ExecuteInEditMode()]
public class Row{
public int[] column;
}
[System.Serializable]
[ExecuteInEditMode()]
public class Array2D{
public Row[] rows;
}
[System.Serializable]
[ExecuteInEditMode()]
public class test : MonoBehaviour {
public int x;
public int y;
public Array2D Tiles;
public bool refresh = false;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if(refresh==true){
setRowCol(x,y);
}
}
void setRowCol(int r,int h){
if(r>0&&h>0){
Tiles.rows = new Row[r];
for(int i=0; i<r;i++){
Tiles.rows[i].column = new int[h];
}
}
if(r==0||h==0){
Debug.Log("0 is not a valid value for X or Y");
}
refresh=false;
}
}
The code works fine for the most part; however, this one line:
Tiles.rows[i].column = new int[h];
Does not work however much I try. Can someone please tell me what the issue is? The error I get is a NullReferenceException.
Answer by KellyThomas · Jan 30, 2014 at 05:50 PM
Tiles.rows = new Row[r];
That line is assigning an array or Rows
but not actually instantiating any instances of Row
. At that point the array holds a set of null values. You then receive an error when you try to access a property of the null in Tiles.rows[0]
.
Instead you should assign a new Row
instance for each position in the rows[]
array, then you can access their properties:
for(int i=0; i<r;i++){
Tiles.rows[i] = new Row();
Tiles.rows[i].column = new int[h];
}
Thank you, I can't believe I missed something as simple as that!
Your answer
![](https://koobas.hobune.stream/wayback/20220613132119im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Material[] Object reference not set when instantiating 2 Answers
Instantiating gameobjects in an array / class problem | NullReferenceException: 0 Answers
Make object move in a direction depending on where it spawns? (C#) 1 Answer
Prefabs instantiated from an array are keeping their public int value 1 Answer
Simultaneous Null Reference Exception and expected value 1 Answer