Search code examples
unity-game-enginenullreferenceexceptionhashset

Unity NullReferenceException Hashset Add


I want to add hashset but the unity pops up NullReferenceException. Hashset is the only store for the non-duplicate value that needed to delete my save game. How to add value to my hashset string without null-reference?

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

My Code

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();
        }
    }

}

Solution

  • Oh ... I got my own answer.

    Just add a null check on my getter.

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

    Don't add a new hashset on mouse click, because it will remove the entire hashset and add a new value. Below is a bad code to add hashset. That's why use getter and add a null check.

        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)}");
    
            }