【问题标题】:Unity: Cannot modify / add values to an array in System.SerializableUnity:无法修改/向 System.Serializable 中的数组添加值
【发布时间】:2021-10-30 18:07:29
【问题描述】:

我有一个 System.Serializable 类

[System.Serializable]
public class _answersData
{
    public string word;
    public string wordmeaning;
    public string wordmeaning2;
    public GameObject result;    
}

然后我有一个 monobehaviour 类,其中声明了一个 _answerData 类的数组

public class gamePlay : MonoBehaviour
{
    public _answersData[] answersData;
}

然后我尝试使用以下方法将数据从另一个脚本添加到 _answerData 数组

public class challengeScript: MonoBehaviour
{
    void Start()
    {
        gameplayScript = gameObject.GetComponent<gamePlay>();
        populate();
    }
    
    void populate()
    {
        answersCount = int.Parse(snapshot.Child("Answers").Child("Count").Value.ToString());
        gameplayScript.answersData = new _answersData[answersCount];

        for (int i = 0; i < answersCount; i++)
        {
            string positionNode = "Answer" + (i + 1).ToString();
            string _word = snapshot.Child("Answers").Child(positionNode).Child("Word").Value.ToString();
            gameplayScript.answersData[i].word = _word;   
        }
    }
}

但我在 'gameplayScript.answersData[i].word = _word' 行收到 NullReferenceException

这是错误:

NullReferenceException:对象引用未设置为对象的实例

有人可以指导我在这里做错了什么吗?

【问题讨论】:

    标签: c# arrays unity3d


    【解决方案1】:

    仅仅因为它是[Serializable] 并不意味着一旦创建数组就会自动创建元素。默认情况下,所有引用类型元素仍将是 null

    只有在 Unity 中,检查器本身才会自动创建 [Serializable] 类型的实例并初始化数组本身。

    在代码中,您必须自己实际创建元素实例,例如

    var answerData = new _answerData();
    answerData.word = _word;
    gameplayScript.answersData[i] = answerData;  
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-03-14
      • 1970-01-01
      • 2018-10-11
      • 2018-07-17
      • 2019-05-27
      • 2018-03-26
      • 2023-01-17
      相关资源
      最近更新 更多