How to get random value from Dictionary<string, bool>
I am trying to get a random game name from my Dictionary Dictionary<string, bool>. Any method I try doesn't seem to work for some reason. I could do this in simple list form and I had this actually but what I am trying to do is in the first scene I want players to choose games they want to play(1 game or multiple games or all games). I have these game names as buttons on the scene in unity and What I'm trying to do is once they click those buttons and hit play only those games should run.
This is the screenshot of my main scene
Tried with ElementAT
Dictio开发者_C百科nary<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);
string gameName = //(here)
You can use the below code using ElementAt
For the sake of testing purposes, I have changed a few values to true in your dictionary.
Dictionary<string, bool> nameOfTheGame = new Dictionary<string, bool>();
nameOfTheGame.Add("Never Have I Ever", true);
nameOfTheGame.Add("Randomiser", false);
nameOfTheGame.Add("Dare", true);
nameOfTheGame.Add("Vote & Win", false);
nameOfTheGame.Add("Who Is Most Likely To ?", true);
nameOfTheGame.Add("Where's the water ?", false);
nameOfTheGame.Add("Would You Rather Choose ?", true);
nameOfTheGame.Add("Flip Or Strip", false);
nameOfTheGame.Add("Two Truths And One Lie", true);
Random rand = new Random();
int index1 = rand.Next(0, nameOfTheGame.Count);
var item = nameOfTheGame.ElementAt(index1).Value;
int index2 = rand.Next(0, nameOfTheGame.Count);
var item2 = nameOfTheGame.ElementAt(rand.Next(0, nameOfTheGame.Count)).Value;
You can do it like this using System.Random
class:
System.Random rand = new System.Random();
int index = rand.Next(map.Count-1);
string name = map.ElementAt(index).Key;
First line initializes random number generator. Second line gets number from 0 to your dictionary length, minus one. Your dictionary has 9 entries, so generated number will be from 0 to 8. Then, by that generated bumber (index) you can get element from your Dictionary
. Once you have an element, Key
contains the name of the game.
精彩评论