unity NullReferenceException Hashset 添加

Unity NullReferenceException Hashset Add

我想添加hashset但是unity弹出NullReferenceException。哈希集是删除我的保存游戏所需的非重复值的唯一存储。如何在没有空引用的情况下向我的哈希集字符串添加值?

Capture Error Null => When ChangeMyString.Add(datetime); orMyString.Add(datetime); => screenshot of my code : ChangeMyString or MyString

我的代码

public class HashsetSource : MonoBehaviour
{
    public HashSet<string> MyString;

    public HashSet<string> ChangeMyString
    {
        get
        {
            return MyString;
        }
        set
        {
            MyString = value;
        }
    }

    private void Update()
    {
        if (Input.GetMouseButtonDown(0))  //Try Store string value of datetime to MyString (HashSet) On left Click
        {
            System.DateTime theTime = System.DateTime.Now;
            string datetime = theTime.ToString("yyyy-MM-dd-HH-mm-ss");
            ChangeMyString.Add(datetime);

            Debug.Log($"DOes the {datetime} exist on? {MyString.Contains(datetime)}");

        }

        if (Input.GetMouseButtonDown(1)) //Try retreive strings on MyString (HashSet) on right click
        {
            foreach (var myString in ChangeMyString)
            {
                Debug.Log(myString);
            }
            
        }

        if (Input.GetMouseButtonDown(2)) //Clear MyString (HashSet) on middle click
        {
            ChangeMyString.Clear();
        }
    }

}

哦...我有自己的答案。

只需在我的 getter 上添加一个空检查。

public HashSet<string> ChangeMyString
{
    get
    {
        if (MyString == null)
        {
            MyString = new HashSet<string>();
        }
        return MyString;
    }
    set
    {
        MyString = value;
    }
}

不要在鼠标单击时添加新的哈希集,因为它会删除整个哈希集并添加新值。下面是添加哈希集的错误代码。这就是使用 getter 并添加空检查的原因。

    private void Update()
    {
        if (Input.GetMouseButtonDown(0))  //Try Store string value of datetime to MyString (HashSet) On left Click
        {
            System.DateTime theTime = System.DateTime.Now;
            string datetime = theTime.ToString("yyyy-MM-dd-HH-mm-ss");
            ChangeMyString = new HashSet<string>();
            ChangeMyString.Add(datetime);

            Debug.Log($"DOes the {datetime} exist on? {MyString.Contains(datetime)}");

        }