在 Unity 中分配键值对时出现 NullReferenceException

NullReferenceException When Assigning Key Value Pair in Unity

我正在尝试使用 UI 函数在 Unity3D 中开发统计分配系统,但我 运行 遇到了一个问题,当我尝试将键值对分配给 IDictionary 时Unity 控制台抛出以下错误

NullReferenceException: Object reference not set to an instance of an object

下面是对应的脚本抛错:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class character_Creation : MonoBehaviour

{

    public InputField characterName;
    public Dropdown stats;
    public Dropdown statSelector;
    public Dropdown raceSelection;
    public Dropdown classSelection;
    public Dropdown alignment;
    public Button submit;
    public Button apply;
    public GameObject menu;
    public GameObject statCreation;
    private IDictionary<int, float> list;
    private float totalRoll;
    private float stat1;
    private float stat2;
    private float stat3;
    private float stat4;
    private float stat5;
    private float stat6;

    public void Awake()
    {
        submit.onClick.AddListener(submitButton);
        apply.onClick.AddListener(applyStat);
    }

    public void submitButton()
    {
        string name = characterName.text;
        string race = raceSelection.options[raceSelection.value].text;
        string myClass = classSelection.options[classSelection.value].text;
        string align = alignment.options[alignment.value].text;

        Debug.Log(name);
        Debug.Log(race);
        Debug.Log(myClass);
        Debug.Log(align);
        Debug.Log("Rolling Character Stats!");
        list.Add(0, diceRoll(6, 3));
        list.Add(1, stat2 = diceRoll(6, 3));
        list.Add(2, stat3 = diceRoll(6, 3));
        list.Add(3, stat4 = diceRoll(6, 3));
        list.Add(4, stat5 = diceRoll(6, 3));
        list.Add(5, stat6 = diceRoll(6, 3));
        PopulateDropdown(stats);
        menu.SetActive(false);
        statCreation.SetActive(true);



    }
    public void applyStat()
    {
        list.Remove(0);
    }

    public float diceRoll(int type, int number)
    {
        totalRoll = 0;
        while (number >= 0)
        {
            float roll = Random.Range(1, type);
            totalRoll += roll;
            number += -1;
        }

        return totalRoll;
    }

    public void PopulateDropdown(Dropdown dropdown)
    {
        List<string> options = new List<string>();
        foreach (KeyValuePair<int, float> option in list)
        {
            options.Add(option.Value.ToString());
        }

        dropdown.ClearOptions();
        dropdown.AddOptions(options);
    }
}

基本上我无法将我的个人统计信息添加到我的词典中,因此我以后可以用所述统计信息填充下拉菜单。

提前感谢您的帮助

通过将 IDictionary 转换为 Dictionary 并将变量列表实际分配​​为 Dictionary 解决了问题。

list = new Dictionary<int, float>();

您似乎从未将对象分配给 "list" 变量(即 list = new Dictionary<int, float>();)。

语句private IDictionary<int, float> list;只声明了一个名为"list"的变量;它实际上并没有给它赋值。