How to properly use randomize() and seed()

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By 4K4deusz
:warning: Old Version Published before Godot 3 was released.

Hello,

I am trying to make build a random generator, so that a deck of cards will be randomized every time you start the scene. I am new to scripting and could do with some pointers or simple examples.

so far I got this working:

extends GridContainer

var RandomNumber = randi()%11


func _ready():
	print (RandomNumber)
	

but it only prints the same number every time. I get the feeling I have to use seed() but not sure how to do that. The docs mentions:

Array rand_seed( int seed )
Random from seed, pass a seed and an array with both number and new seed is returned.


float randf()
Random value (0 to 1 float).


int randi()
Random 32 bits value (integer). To obtain a value from 0 to N, you can use remainder, like (for random from 0 to 19): randi() % 20.


Nil randomize()
Reset the seed of the random number generator with a new, different one.

Any help/explanation would be appreciated.

Thanks
4k4deusz

:bust_in_silhouette: Reply From: Calinou

This should work:

extends GridContainer

func get_random_number():
    randomize()
    return randi()%11

func _ready():
    print(get_random_number())

This is the simplest solution I know of. You can’t put randomize() outside of a function (only variable declarations and comments are allowed outside of functions in GDScript, pretty much).

Thank you soo much!

4K4deusz | 2016-10-28 14:20

I have a global setup as a singleton (loaded in project settings) and I put randomize in it’s _ready function so that it only needs to be called once.

jarlowrey | 2018-02-15 23:41

You shouldn’t do this, as it can cost performance.
As stated in the docs, you should call randomize() only once:
Random number generation — Godot Engine (stable) documentation in English

Kirito | 2023-03-16 18:23