my code works just fine with 1D array but when i try to make a 2D array i get an error message
the error message :
NullReferenceException: Object reference not set to an instance of an object
this is my code :
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]);
}
}
the CoreManager class :
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;
}
What your trying to build here is a Jagged Array . For each additional dimensions of the jagged array, you also need to create an instance of it. In your case, it would look like:
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]);
Here's the Microsoft docs on Jagged Arrays.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.