Unity NullReferenceException哈希集添加



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

捕获错误Null=>当CCD_ 1或CCD_;我的代码截图:ChangeMyString或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上添加一个null检查。

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

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

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

最新更新