0

我最后一个问题的另一个后续问题。

我已经设置了我的字典,我正在从另一个设备传递键值和距离值。我希望我的程序根据距离值更新一些局部变量,但只更新那些与字典中的键号相关联的变量。

所有这些代码如下所示:

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

这样就不会检查数组中的第一条消息并将其传递给两者之间的每个可能的组合。系统中仍然存在同样的问题。

任何人都可以看到任何东西吗?

4

1 回答 1

1

也许我误读了您的代码,但设置 myDictonary[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;
   }
}
于 2013-11-05T17:51:29.733 回答