Unity中如何从Dictionary<string, bool>获取选中的随机游戏名称?
解决方案:从选中的游戏中随机获取名称
实现思路
- 从字典里筛选出所有被选中的游戏名称(即
value为true的key) - 检查筛选结果是否为空,避免无选中游戏时出现报错
- 用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
相关产品推荐
相关产品推荐

