Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get a random variant of an enum in GDScript, Godot 3.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?

like image 865
Newbyte Avatar asked Sep 12 '25 21:09

Newbyte


1 Answers

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 [].

like image 135
Newbyte Avatar answered Sep 15 '25 12:09

Newbyte