用这种方法可以通过值找键,前提是字典中存储的值不能相同。虽然在各种使用配置文件的游戏里面这种方法可能很少使用,但是我们是可以使用 LINQ 扩展方法来根据字典的值查找对应的键的。
下面通过一个实例来说明如何通过键查找值以及如何通过值查找键。
注意:下面使用NGUI,(当然UI不受影响)其中一些UI是输入文本框以及一些文本。
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public class Play : MonoBehaviour
{
public UIInput aInput;
public UIInput bInput;
public UILabel cLable;
public int text;
public Dictionary<string, int> dList=new Dictionary<string, int>();
private void Start()
{
dList.Add("zero", 0);
dList.Add("one", 1);
dList.Add("two", 2);
dList.Add ("three", 3);
dList.Add ("four", 4);
dList.Add("five", 5);
dList.Add("six", 6);
dList.Add("seven", 7);
dList.Add("eight", 8);
dList.Add("nine", 9);
dList.Add("ten", 10);
dList.Add("eleven", 11);
dList.Add("twelve", 12);
dList.Add("thirteen", 13);
dList.Add("fourteen", 14);
dList.Add("fifteen", 15);
dList.Add("sixteen", 16);
dList.Add("seventeen", 17);
dList.Add("eighteen", 18);
dList.Add("nineteen", 19);
dList.Add("twenty", 20);
}
private void Update()
{
if (aInput.value != null || bInput.value != null) {
text = GetValue(aInput.value);
text+=GetValue(bInput.value);
} cLable.text=dList.FirstOrDefault(x=>x.Value==text).Key;
}
public int GetValue(string engNum)
{
int value=0;
dList.TryGetValue(engNum, out value);
return value;
}
}
以上脚本中,通过值获取键的核心代码为:
cLable.text=dList.FirstOrDefault(x=>x.Value==text).Key;
通过键获取值的核心方法为:
public int GetValue(string engNum)
{
int value=0;
dList.TryGetValue(engNum, out value);
return value;
}
字典内部的值是我任意存储的,(或者写成配置文件的形式)你当然可以自行优化代码或者修改代码,希望我的回答对你的游戏开发有所帮助,喜欢就点赞收藏吧!