How to change enum state randomly

Godot Version

<stable4.2>

Question

<how do you pick enum state randomly? I want to let enemy to pick next state randomly. >

enum State { Idle, Walk, Attack }

var nextState: State = randi_range(0, State.size() - 1)
print("Next state is ", State.keys()[nextState], "!")
1 Like

what exactly is .size()?

An enum in GDScript works just like a constant Dictionary, which means .size() returns the number of elements of State.

By the way, I made some errors in the second line, I corrected them now.

what if i want to choose from certain state but not from all ?

Make an array with the states you want and pick a random element, for example:

var nextState: State = [ State.Idle, State.Walk ].pick_random()
1 Like