Godot Version 4
Question
I’m trying to randomize instantiating between 3 scenes, and this is the method I’ve found so far (that works):
Does anyone have any recommendations on how to make this code better? I’m accepting all sugestions… Thanks!
I’m trying to randomize instantiating between 3 scenes, and this is the method I’ve found so far (that works):
Does anyone have any recommendations on how to make this code better? I’m accepting all sugestions… Thanks!
Hey @kiromyn , maybe u can try this approach:
var layouts : Array[PackedScene]
const LAYOUT_1 = preload("res://scenes/layouts/layout_1.tscn")
const LAYOUT_2 = preload("res://scenes/layouts/layout_2.tscn")
const LAYOUT_3 = preload("res://scenes/layouts/layout_3.tscn")
const CORNER = Vector2(80,45)
var time:= 0.0
func _ready() -> void:
# preferable dont do like this, try to export the layout var
# and add it in the UI or another approach
layouts.append_array([LAYOUT_1, LAYOUT_2, LAYOUT_3])
func _process(delta: float) -> void:
time += 10.0 * delta
print(time)
if time >= 30.0:
var random = randi() % len(layouts)
instantiate_layout(layouts[random])
time = 0.0
func instantiate_layout(layout: PackedScene):
var instance = layout.instantiate()
instance.position = CORNER
add_child(instance)
This approach will get the layout in an array by it’s index, so it will always obey the order of it.
You could also try to use a Dictionary
instead and use named key to it.
The biggest benefit of this approach is not having to write all those if statements and make it scalable as far as u keep adding layouts.
Thank you so much, that’s a lot better!