I set up a serializable field with 2 layers, try to resize the array inside the layer and add value in a specific element.
Than the “NullReferenceException: Object reference not set to an instance of an object” error will come out and can’t set the new value.
But if the code not in same function, that work fine
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Listtest : MonoBehaviour
{
public Layer1s[] Layer1;
[System.Serializable]
public class Layer1s
{
public Layer2s[] Layer2;
[System.Serializable]
public class Layer2s
{
public string Layer2_name;
}
}
public void Start()
{
Layer1[0].Layer2 = new Layer1s.Layer2s[5];
Layer1[0].Layer2[3].Layer2_name = "something";
}
public void Addvalue()
{
Layer1[0].Layer2[3].Layer2_name = "something";
}
}
Self answer this question.
Just get informed by this answer
https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it
The “Array Elements” section
Person[] people = new Person[5];
people[0].Age = 20 // people[0] is null. The array was allocated but not
// initialized. There is no Person to set the Age for.
and this question
https://stackoverflow.com/questions/28290757/get-null-reference-exception-after-initialize-the-array
I realize after after initialize the array, still need to initialize the array element
And this finally work for me:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Listtest : MonoBehaviour
{
public Layer1s[] Layer1;
[System.Serializable]
public class Layer1s
{
public Layer2s[] Layer2;
[System.Serializable]
public class Layer2s
{
public string Layer2_name;
}
}
public void Start()
{
Layer1[0].Layer2 = new Layer1s.Layer2s[5];
Layer1[0].Layer2[3] = new Layer1s.Layer2s();//Initialize the second layer array elements
Layer1[0].Layer2[3].Layer2_name = "something";
}
}