我的代码在1D数组上正常工作,但是当我尝试制作2D数组时,我收到一条错误消息
错误消息:
NullReferenceException: Object reference not set to an instance of an object
这是我的代码:
public class NewBehaviourScript : MonoBehaviour
{
public CoreManager[] mng2 = new CoreManager[5];
public CoreManager[][] mng = new CoreManager[5][];
void Start()
{
//this code works fine
mng2[1].actual_words = new string[5];
mng2[1].actual_words[0] = "test 1 ";
Debug.Log(mng2[1].actual_words[0]);
//this code gives me the error message
mng[0][0].actual_words = new string[5]; // the error message is about this line
mng[0][0].actual_words[0] = "test 2 ";
Debug.Log(mng[0][0].actual_words[0]);
}
}
CoreManager类:
public class CoreManager
{
[Tooltip("Write these words in actual sequence of the sentence")]
public string[] actual_words;
[Tooltip("Write these words in any sequence of the sentence")]
public string[] mixed_words;
}
答案 0 :(得分:4)
您尝试在此处构建的是锯齿状阵列。对于锯齿状数组的每个其他维,您还需要为其创建一个实例。就您而言,它看起来像:
mng[0] = new CoreManager[number of elements you want];
mng[0][0] = new CoreManager();
mng[0][0].actual_words = new string[5]; // the error message is about this line
mng[0][0].actual_words[0] = "test 2 ";
Debug.Log(mng[0][0].actual_words[0]);
这是锯齿阵列上的Microsoft docs。