+1 vote

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():
    randomize()
    #tiles_goal = current_base * (randi() % max_multiplier + 1)
    print(tiles_goal)
Godot version 3.5
related to an answer for: How to properly use randomize() and seed()
in Engine by (46 points)

1 Answer

+2 votes
Best answer

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?

by (731 points)
selected by

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():
    randomize()
    tiles_goal = current_base * (randi() % max_multiplier + 1)

Yes, that all seems correct

Thank you very much!

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.