在Unity中通过字典的值查找相应的键(C#)

用这种方法可以通过值找键,前提是字典中存储的值不能相同。虽然在各种使用配置文件的游戏里面这种方法可能很少使用,但是我们是可以使用 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;
    }

字典内部的值是我任意存储的,(或者写成配置文件的形式)你当然可以自行优化代码或者修改代码,希望我的回答对你的游戏开发有所帮助,喜欢就点赞收藏吧!

  • 11
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Nicole Potter

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值