Randomizing a list

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

When I try to randomize the list it always gives the same results here is what I used

func choose_random(rand_list):
	return rand_list.pop_front()
:bust_in_silhouette: Reply From: dancaer69

I think you must use randomize() method. This needed when use rand, randi etc methods, so probably shuffle() needs it too.

:bust_in_silhouette: Reply From: Calinou

To get a random element from an array faster, use the following instead:

# Make sure to call `randomize()` once (and only once) in a script's `_ready()` function first.
# Don't call `randomize()` multiple times as it will slow things down.
func choose_random(rand_list):
    return rand_list[randi() % rand_list.size()]

This is because you don’t need to shuffle the whole array to get a single random element from it.

If you need to do this a lot, consider inlining this function where you need it instead of creating a dedicated function, as function calls are relatively slow in GDScript (and cannot be inlined by the compiler as of writing).