0 votes

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()
in Engine by (25 points)

2 Answers

+4 votes
Best answer

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).

by (12,651 points)
selected by
+1 vote

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

by (221 points)
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.