Topic was automatically imported from the old Question2Answer platform.
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)
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.