You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity中如何从Dictionary<string, bool>获取选中的随机游戏名称?

解决方案:从选中的游戏中随机获取名称

实现思路

  1. 从字典里筛选出所有被选中的游戏名称(即value为true的key)
  2. 检查筛选结果是否为空,避免无选中游戏时出现报错
  3. 用Unity的Random.Range方法从筛选后的列表中随机选取一个名称

完整代码示例

Dictionary<string, bool> nameOfTheGame = new Dictionary<string, bool>();

nameOfTheGame.Add("Never Have I Ever", false);
nameOfTheGame.Add("Randomiser", false);
nameOfTheGame.Add("Dare", false);
nameOfTheGame.Add("Vote & Win", false);
nameOfTheGame.Add("Who Is Most Likely To ?", false);
nameOfTheGame.Add("Where's the water ?", false);
nameOfTheGame.Add("Would You Rather Choose ?", false);
nameOfTheGame.Add("Flip Or Strip", false);
nameOfTheGame.Add("Two Truths And One Lie", false);

// 筛选出玩家选中的游戏
List<string> selectedGames = nameOfTheGame.Where(kv => kv.Value).Select(kv => kv.Key).ToList();

string gameName = string.Empty;
if (selectedGames.Count > 0)
{
    // 随机选取一个选中的游戏
    int randomIndex = UnityEngine.Random.Range(0, selectedGames.Count);
    gameName = selectedGames[randomIndex];
}
else
{
    // 无选中游戏时的处理逻辑,可根据需求修改
    Debug.Log("请至少选择一个游戏!");
}

关键注意点

  • 必须使用UnityEngine.Random而非System.Random,Unity的随机数生成器更适配游戏场景,且与编辑器随机状态同步
  • 必须判断selectedGames的数量,否则无选中游戏时访问索引会触发越界异常

内容的提问来源于stack exchange,提问作者Pyromancer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 04:15:42