How to pick a random integer from an Array?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Martik

I have this array:

var options = [1,2,3,4]

How to make it choose random under an If statement?

:bust_in_silhouette: Reply From: eod
randomize()
var options = [1,2,3,4]
var rand_index:int = randi() % options.size()

if options[rand_index]:
    print options[rand_index]
:bust_in_silhouette: Reply From: TheoTheTorch

Here’s a better solution:

var rand_value = my_array[randi() % my_array.size()]

It’s just 1 line and all you need beforehand is an array. EG:

# var my_array = [0, 1, 2, 3]

In Godot 4 you can use array.pick_random().

var my_array = [1,2,3,4]
var rand_value = my_array.pick_random()