Spawning scenes randomly from array.

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

Hello guys. I wrote this code to spawn objects randomly from an array of scenes. I did make them spawn but it spawns all four objects randomly per timeout instead of one. Here’s the code:

extends Node

var blue = preload(“res://Scenes/blue.tscn”)
var green = preload(“res://Scenes/green.tscn”)
var red = preload(“res://Scenes/red.tscn”)
var plat = preload(“res://Scenes/Platform.tscn”)

func _ready() → void:
pass

func _on_spawn_timer_timeout() → void:
randomize()
var platforms = [blue, red, green, plat]
for x in platforms:
var object = x.instance()
print (object)
object.position = Vector2(500, rand_range(0, 600))
add_child(object)

:bust_in_silhouette: Reply From: jgodfrey

Yeah, you’re specifically iterating through the array of scenes and creating an instance of each one. It sounds like, instead, you want to randomly choose one of the scenes each time the code is called. Here’s some adjusted code (though, adjusted in the post and untested):

func onspawntimertimeout() -> void:
    randomize()
    var platforms = [blue, red, green, plat]
    var platform = platforms[randi() % platforms.size()]
    var object = platform.instance()
    print (object)
    object.position = Vector2(500, randrange(0, 600))
    addchild(object)

And, I should have noted, this is the most important bit…

var platform = platforms[randi() % platforms.size()]

That chooses a random number in the same range as the indices in the platforms array. Then, using that number, it chooses one of the platforms.

jgodfrey | 2020-02-17 15:22

Genius. It worked. Thank you for explaining it. I haven’t come across something like this before.

grey_lotus | 2020-02-17 16:12

I haven’t come across something like this before.

You might want to check the tutorials then:
Your first game — Godot Engine (3.2) documentation in English

A lot of the questions here wouldn’t be asked if people read the tutorials. They cover a lot of the basics and some interesting and helpful practices.

Bernard Cloutier | 2020-02-19 18:01