How to index into string array and print indexed string in game directions?

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

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.

Can you show me the random number generator code?

Skyfrit | 2020-11-03 07:46


extends Node

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

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

miss_bisque | 2020-11-03 16:29

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()]

Skyfrit | 2020-11-03 18:34

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?

miss_bisque | 2020-11-03 21:07