Because you didn’t explicitly set the integral type of the enum, it defaults to int. If you don’t explicity set the values of the enums, the first element in the sequence is 0 and +1 for each going down.
You can do(assuming the variable cardSuit is of type CardSuit(the enum):
One more example that once again only applies to enums that haven’t had their default values set. We know we start at 0, but perhaps we don’t want to explicity set the max, you may end up updating the enum with more elements and that would require additional maintenance. Lets remove that extra step. System.Linq is required as a using.
@thef1chesser it has to be values.Length since Random.Range never returns max value as the random number, so value.Length - 1 will never yield the last value.
Use this utility method in some Utility static class:
public static T RandomEnumValue<T>()
{
var values = Enum.GetValues(typeof(T));
int random = UnityEngine.Random.Range(0, values.Length);
return (T)values.GetValue(random);
}
Then, use it in your game class like this:
private enum MyEnum
{
One,
Two,
Three
}
private void Method()
{
MyEnum e = Utility.RandomEnumValue<MyEnum>();
}
I think you should subtract 1 from your array length when generating random value, otherwise you may end up with IndexOutOfRangeException
[Random.Range][1] takes only two arguments i.e. min and max value which is the range in which any random number will be generated. [1]: http://docs.unity3d.com/ScriptReference/Random.Range.html
– HarshadK