Using randi() in a global variable

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

So I’m trying to use randi() in a global variable. ready() prints always the same value. (Note that when uncommenting the second line inside of ready() it does print a random one)
Already tried without the “onready” preffix. Nothing works.

extends Node

var max_multiplier = 5

#This variable has to dynamically change during the game
var current_base = 4

onready var tiles_goal = current_base * (randi() % max_multiplier + 1)

func _ready():
	#tiles_goal = current_base * (randi() % max_multiplier + 1)
:bust_in_silhouette: Reply From: SQBX

onready variables are defined before the actual _ready() function. Assign it inside the function instead, after calling randomize()

It seems you already tried doing this, though, and ended up commenting it out. Was there a problem?

Yes. I’d like tiles_goal to be a global variable.
Declaring it globally and assigning the value inside of _ready() seems to be the solution. Right?

var tiles_goal
var max_multiplier = 5
var current_base = 4

func _ready():
    tiles_goal = current_base * (randi() % max_multiplier + 1)

gonzalezharry | 2022-12-31 20:38

Yes, that all seems correct

SQBX | 2022-12-31 20:39

Thank you very much!

gonzalezharry | 2022-12-31 20:43