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

时间:2019-04-28 00:43:41

标签: c# unity3d idictionary

我正在尝试使用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>();

1 个答案:

答案 0 :(得分:1)

您似乎从未向“列表”变量(即list = new Dictionary<int, float>();)分配对象。

语句private IDictionary<int, float> list;仅声明一个名为“ list”的变量;它实际上并没有为其分配值。