Awaitng every time a function is ran

Godot Version

4.2.2

Question

in my game I need an object to wait for 0.3 seconds every time when it is told to spawn but the await only runs on the first time the function is ran

Currently this is my code

extends Node3D
var car = preload("res://Formula car.tscn")

# Called when the node enters the scene tree for the first time.
func _ready():
	await get_tree().create_timer(30).timeout
	queue_free()

# Called every frame. 'delta' is the elapsed time since the previous frame.

func _process(delta):
	var spawnchance = randi_range(0,2)
	var new_car = car.instantiate()
	if spawnchance == 1:
		wait(0.3)
		add_child(new_car)
	
	
func wait(seconds: float) -> void:
	await get_tree().create_timer(seconds).timeout

Calling a function without await will not wait for it to finish. Try

await wait(0.3)

Though it’s strange to have such waits in a _process function, even a 1 in 3 chance every frame of something happening.

1 Like

It still might be sleep talking, but the logic I’m seeing here is:

  • Spawn a race care scene for 30 sec then destroy it.
    – During that time, every 0.3 second spawn a car class (probably a class).
    — Which mean, in total, 100 cars.

Which if I got it right, seems a bit… weird? I’d say. Nonetheless, instead of “await,” why don’t you use simple Timers with a callback after the period of time you want that will call a spawner or a remover method.

That’s what I would do, but then again, only you know your project.

2 Likes

Thanks New to Godot and game development and forgot the timer existed

1 Like