If I have a vector of strings and want to store a random one in a variable, how can I do that? Is there any C# built-in function for this?
How to randomize a string variable
C# has a built-in random number generator, many games end up with something a little more custom.
In general you create a new random number generator somewhere in your code.
Random generator = new Random();
You use the generator wherever you need a source of random numbers. In this case you can use Next() which has several signatures. Next(x) returns an integer between 0 and (x-1), so Next(100) would return a random value in the range 0-99. Another, Next(x,y) returns an integer between x and y-1, so Next(50,100) returns a value in the range 50-99.
Since you're looking for an index in your list:
{
int randomIndex = generator.Next(mystrings.Count());
return mystrings[randomIndex];
}
Therefore, you shouldn’t make that “somewhere” in “create a new random number generator somewhere in your code” be immediately before its use, but rather, as a member variable initialized at load-time.
You use the generator wherever you need a source of random numbers. In this case you can use Next() which has several signatures. Next(x) returns an integer between 0 and (x-1), so Next(100) would return a random value in the range 0-99. Another, Next(x,y) returns an integer between x and y-1, so Next(50,100) returns a value in the range 50-99.
I probably don't know enough about the libraries used or I'm missing something else, but I get this error 'Random does not contain a definition for <Next> and no extension method <Next> accepting a first argument of type <Random> could be found.'.
https://msdn.microsoft.com/en-us/library/2dx6wyd4(v=vs.110).aspx
What tools are you using (Visual Studio, etc?)
Dumb question: did you "using System;" at the top of your .CS file?
Yes, I was using System.
There seemed to be a problem with System.Random and UnityEngine.Random. Fixed it now by specifying everywhere I used a 'Random' function which library to use.
Thank you all for the help.
For numbers Random,
You could also use GUID.
A GUID is not usable directly as an index into a list of strings, which is what the OP asked for.