I’m currently porting over a game from Construct 2, which has a “Choose” function, as described here:
choose(a, b [, c…])
Choose one of
the given parameters at random. E.g.
choose(1, 3, 9, 20) randomly picks one
of the four numbers and returns that.
This also works with strings, e.g.
choose(“Hello”, “Hi”) returns either
Hello or Hi. Any number of parameters
can be used as long as there are at
least two.
What would be the simplest way to implement something like this in C#?
public T Choose<T>(T a, T b, params T[] p)
{
int random = Random.Range(0, p.Length + 2);
if (random == 0) return a;
if (random == 1) return b;
return p[random - 2];
}
I would just set up an array containing the elements that can be chosen from (whether strings or ints or whatever). Then choose a random number from a range representing the length of the array, then use that value to call up the element. For instance, if your array is (“hello”, “hi”, “greetings”) and the random number is chosen is 1 then element 1 from your array (“hi”) is passed.