【问题标题】:I am trying to insert data into a 2D array of objects我正在尝试将数据插入到对象的二维数组中
【发布时间】:2021-02-21 21:48:30
【问题描述】:

我的代码适用于一维数组,但是当我尝试制作一个二维数组时,我收到一条错误消息

错误信息:

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;

}

【问题讨论】:

    标签: c# arrays visual-studio unity3d object


    【解决方案1】:

    您在这里尝试构建的是一个锯齿状阵列。对于锯齿状数组的每个附加维度,您还需要创建它的一个实例。在您的情况下,它看起来像:

    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

    【讨论】:

    • 我只是在尝试修复,但仍然收到相同的错误消息
    • 我通过添加以下代码解决了这个问题:mng[0][0] = new CoreManager();
    • @mamonjaran 你是对的,是的。更新了代码以反映这一点。
    猜你喜欢
    • 1970-01-01
    • 2021-08-14
    • 2015-08-09
    • 1970-01-01
    • 2019-08-08
    • 2022-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多