3

I have declared an enum like so in GDScript:

enum State = { STANDING, WALKING, RUNNING }

I want to get a random variant of this enum without mentioning all variants of it so that I can add more variants to the enum later without changing the code responsible for getting a random variant.

So far, I've tried this:

State.get(randi() % State.size())

And this:

State[randi() % State.size()]

Neither work. The former gives me Null, and the latter gives me the error "Invalid get index '2' (on base: 'Dictionary')."

How might I go about doing this in a way that actually works?

Newbyte
  • 2,421
  • 5
  • 22
  • 45

1 Answers1

5

This can be achieved the following way:

State.keys()[randi() % State.size()]

This works because keys() converts the State dictionary to an array, which can be indexed using [].

Newbyte
  • 2,421
  • 5
  • 22
  • 45