0 votes

I have a random number generator that creates an array of 3 random numbers at the beginning of my game (it autoloads). For example, the script returns numbers [0 1 8]. I want to use those numbers to index into an array of strings, and print the indexed string during my game directions.

var randN = GetRandomNumber.sample    #returns number array [X X X]

var object_labels = ["bowl", "bread", "cheese_grater", "clock", "cup", "pot", "straws",  "tissue_paper", "toilet_paper", "tooth_paste"]      #strings to use in game

var object_avoid_idx = randN[randi()%randN.size()]     #index into the number array 

func _physics_process(delta):

elif !start and !end:       
     $gameOver.set_text("Avoid the " + str(object_labels[object_avoid_idx]))    
# end text  else:       
     $gameOver.set_text("Game Over!")

I am thinking that when I create the variable object_avoid_idx it will be an index from the randN array. For example, if my randN array = [0 1 8] then object_avoid_idx will be equal to either 0, 1, or 8 depending on the the number chosen in randi()%randN.size().

However, when I run the program I get an error that says Division By Zero in operator '%'.

Any thoughts on how to tweak this? Thanks!

p.s i've cut some code out of the func _physics_process(delta): for brevity.

in Engine by (45 points)

Can you show me the random number generator code?


extends Node

var list = range(0,10)
var sample =[]

func _ready():
    for i in range(3):
        var x = randi()%list.size()

Ok, It seems that object_avoid_idx created before GetRandomNumber is ready.

So, change

var object_avoid_idx = randN[randi() % randN.size()]


onready var object_avoid_idx = randN[randi() % randN.size()]

That worked! Thank you! Just to clarify for the future - when in the game does onready var object initialize a variable as opposed to just having var object?

Please log in or register to answer this question.

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 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 webmaster@godotengine.org with your username.