Perhaps a second timer;

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

Let’s suppose that we have the following code:

extends Node2D

var SPAWN_TIME=2
var spawn_time_left: float=SPAWN_TIME

func spawn_item():

var new_Baby=load("res://spawneritem.tscn")
var ins=new_Baby.instance()
add_child(ins)

func spawn_item2():

var new_Baby2=load("res://spawneritem2D.tscn")
var ins2=new_Baby2.instance()
add_child(ins2)

func _process(delta):

if spawn_time_left<.0:
	spawn_item()
	spawn_item2()
	spawn_time_left=SPAWN_TIME
else:
	spawn_time_left -=delta

Obviously ,with the above code, i create together two objects every 2 seconds.

If I want the Baby for example to be created in 2 seconds but the Baby2 to be created in 1 second, what i can to do?I have to create a second timer or something?

Thank you.

:bust_in_silhouette: Reply From: wombatstampede

You’re actually not using a “Timer” at the moment while what you’re doing isn’t wrong.

If you want to keep it this way then just add a newspan_time_left2 variable and handle it like the first variable (in a separateif clause) just assigning a differentSPAWN_TIME.

You could however also use two Timer nodes instead. With different wait times which trigger the spawn_item in their two timeout event handlers.

Thank you very much!

Nick888 | 2019-06-06 10:39

:bust_in_silhouette: Reply From: Thomas Karcher

Yes, having two timers would probably be the best way to do it, but I’d rather use Timer objects instead of simulating these timers in the _process function. This way, it’s easier to start and stop them as needed and to add more timers with just one line of code:

func _ready():
    var t1 = create_spawn_timer ("spawn_item", 2)
    var t2 = create_spawn_timer ("spawn_item2", 1)

func create_spawn_timer (spawn_func, spawn_time) -> Timer:
    var timer = Timer.new()    
    add_child (timer)
    timer.set_wait_time (spawn_time)
    timer.connect("timeout", self, spawn_func) 
    timer.start()
    return timer

Thank you very much!

Nick888 | 2019-06-06 10:39