- Home /
Answer by DaveA · Apr 04, 2011 at 09:49 PM
Since it's just two choices:
state = Random.value < .5 ? State.Left : State.Right;
Thx m8 worked just fine :) And thx to others too, Tried "state = GetRandomEnum();"
But didnt work.
Just a note: if you have more than two choices, you could use casting, but you should make sure you know the $$anonymous$$ and max values of the enums, and that there are no 'holes' in the sequence.
Answer by Bunny83 · Apr 05, 2011 at 01:01 AM
Well the two solutions here will work in your case, but since enums are not restricted to sequential values here's a general approach (C#):
I just wrote a little generic helper function that will select a random enum member.
static T GetRandomEnum<T>()
{
System.Array A = System.Enum.GetValues(typeof(T));
T V = (T)A.GetValue(UnityEngine.Random.Range(0,A.Length));
return V;
}
And here's a little example:
enum MyEnum { Dog = 1, Cat = 2, Cow = 502, Bird = 621 }
MyEnum choice = GetRandomEnum<MyEnum>();
And in your case you could do:
state = GetRandomEnum<State>();
could you please explain this a bit, mostly what the T means in static T GetRandomEnum()
it works but I do not know what the T is for and why a static is required ins$$anonymous$$d of a class.
@Dark_$$anonymous$$oo: This is a generic function. The type-parameter T allows the function to work with different types ins$$anonymous$$d of one. The return type of the function (which is T) will vary on how you call the function.
Unity has also a page which explains generic methods briefly
This is a good answer to the general problem. Thanks!
Answer by KeithK · Apr 04, 2011 at 09:21 PM
Give this a bash.
EDIT: Added + 1 to the Max parameter of Random.Range(), as per Peter's comment.
state = Random.Range((int)State.Left, (int)State.Right + 1);
Random.Range() is exclusive on the max value, so it will never be chosen if you do that.
Your answer
Follow this Question
Related Questions
Rigidbody2d Moving up and Down but not left and right 1 Answer
Skybox - Left and Right is swapped, needs fixing. 1 Answer
Pay animation if joystick pushed to left and another if joystick is pushed to right 2 Answers
how to control player movement with ui buttons? 1 Answer
Sprite tilts left/right depending on how far it is from the center [C#] 1 Answer