Instantiate a random object while running

Godot Version


Looking for a better way to do this

I am trying to load a random object from a list. What I have doesn’t work. I could use a case statement but eventually stuff will be a huge list that is called often. Is there a better way to do this?

var aaa = preload(“res://src/aaa.tscn”)
var bbb = preload(“res://src/bbb.tscn”)
var ccc = preload(“res://src/ccc.tscn”)

var stuff = [ “aaa”, “bbb”, “ccc” ]

_process(delta) {
var selected = str(stuff[(randi_range(0, 2)])
var new_thing = selected.instantiate()
new_thing.global_position = Vector2(10,10)

var stuff = [ “aaa”, “bbb”, “ccc” ]


var stuff = [ aaa, bbb, ccc ]

you declared and filled variables, and there are strings in your array

and here you are trying to instantiate the string again

do something like this

var stuff = {
	0: preload("scene1.tscn"),
	1: preload("scene2.tscn"),
	2: preload("scene3.tscn")

and then just randomly select the key

var new_thing = stuff[randi_range(0, 2)].instance()

Ugh…yeah time for bed. Should have just stepped away for a bit.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.