C# 更新字典值问题
我设置了我的字典,我正在从另一台设备传入键值和距离值。我希望我的程序根据距离值更新一些局部变量,但只更新那些与字典中的键号相关联的变量 所有这些代码如下所示:C# 更新字典值问题,c#,string,dictionary,unity3d,C#,String,Dictionary,Unity3d,我设置了我的字典,我正在从另一台设备传入键值和距离值。我希望我的程序根据距离值更新一些局部变量,但只更新那些与字典中的键号相关联的变量 所有这些代码如下所示: Dictionary<string, string> myDictonary = new Dictionary<string, string>(); string Value1 = ""; string Value2 = ""; string Value3 = ""; string Value4 = ""; str
Dictionary<string, string> myDictonary = new Dictionary<string, string>();
string Value1 = "";
string Value2 = "";
string Value3 = "";
string Value4 = "";
string Value5 = "";
string Value6 = "";
void Start()
{
myDictonary.Add("11111111", Value1);
myDictonary.Add("22222222", Value2);
myDictonary.Add("33333333", Value3);
myDictonary.Add("44444444", Value4);
myDictonary.Add("55555555", Value5);
myDictonary.Add("66666666", Value6);
}
private void AppendString(string message)
{
testMessage = message;
string[] messages = message.Split(',');
foreach(string w in messages)
{
if(!message.StartsWith(" "))
outputContent.text += w + "\n";
}
messageCount = "RSSI number " + messages[0];
uuidString = "UUID number " + messages[1];
if(myDictonary.ContainsKey(messages[1]))
{
myDictonary[messages[1]] = messageCount;
}
}
void OnGUI()
{
GUI.Label(new Rect(100, Screen.height/2 + 100, 150, 100), "value 1 " + Value1);
GUI.Label(new Rect(100, Screen.height/2 + 120, 200, 100), "value 2 " + Value2);
GUI.Label(new Rect(100, Screen.height/2 + 140, 250, 100), "value 3 " + Value3);
GUI.Label(new Rect(100, Screen.height/2 + 160, 300, 100), "value 4 " + Value4);
GUI.Label(new Rect(100, Screen.height/2 + 180, 350, 100), "value 5 " + Value5);
GUI.Label(new Rect(100, Screen.height/2 + 200, 400, 100), "value 6 " + Value6);
}
在我从中实施修复之前,虽然它可能是错误的,但字符串确实更新并显示在我的屏幕上。自从我把新代码放进去以后,什么也没发生
我已尝试更改以下方法:
if(myDictonary.ContainsKey(messages[1]))
{
myDictonary[messages[1]] = messageCount;
}
因此,不是数组中的第一条消息得到检查,而是传递给这两条消息之间的所有可能组合。系统中仍然存在同样的问题
有人能看到什么吗?也许我误读了您的代码,但是设置MyDictional[messages[1]]=messageCount对字符串变量Value1到Value5的值没有影响。设置字典值将替换与键关联的对象。它不会更改最初与键关联的对象变量的内部值 请尝试以下操作:
void OnGUI()
{
GUI.Label(new Rect(100, Screen.height/2 + 100, 150, 100), "value 1 " + myDictonary["11111111"]);
GUI.Label(new Rect(100, Screen.height/2 + 120, 200, 100), "value 2 " + myDictonary["22222222"]);
GUI.Label(new Rect(100, Screen.height/2 + 140, 250, 100), "value 3 " + myDictonary["33333333"]);
GUI.Label(new Rect(100, Screen.height/2 + 160, 300, 100), "value 4 " + myDictonary["44444444"]);
GUI.Label(new Rect(100, Screen.height/2 + 180, 350, 100), "value 5 " + myDictonary["55555555"]);
GUI.Label(new Rect(100, Screen.height/2 + 200, 400, 100), "value 6 " + myDictonary["66666666"]);
}
或者更好:
void OnGUI()
{
int top = 100;
int left = 150;
foreach(var keyValue in myDictonary) {
GUI.Label(new Rect(100, Screen.height/2 + top, left, 100), keyValue.Key + " " + keyValue.Value);
top += 20;
left += 50;
}
}
如果你上一个问题的答案不起作用,你为什么接受它作为答案,而不是在对该答案的评论中解释它为什么不起作用?