Can i create a coroutine await amount of time without get_tree()

Godot Version

4.3

Context

I call a function from the script that is not attach to any node on scene. So i can’t use get_tree to create timer like this:
image

Question

Is there any way that func can await amount of time without get_tree()?

If your player is a node then you can use their scene tree

await player.get_tree().create_timer(player.DASH_TIME).timeout

But no I don’t think the GDscript scheduler tracks time on it’s own and needs a supplimental timer, which so far only exists on the scene tree.

1 Like

Oh, thank you. I just wonder if there is the way not using get_tree().
Thank you so much for solution anyway.

Use Engine.get_main_loop() to get the scene tree outside of a node script

2 Likes

Oh, i didnt know it exited, thank you

1 Like

Method 1: Using Engine.get_main_loop()

func wait_time_method1(seconds: float) → void:
var scene_tree = Engine.get_main_loop()
if scene_tree:
await scene_tree.create_timer(seconds).timeout

Method 2: Using SceneTree directly

func wait_time_method2(seconds: float) → void:
var scene_tree = get_tree() if “get_tree” in self else Engine.get_main_loop()
if scene_tree:
await scene_tree.create_timer(seconds).timeout

Example usage

func some_function() → void:
print(“Starting”)
await wait_time_method1(2.0) # Waits 2 seconds
print(“After delay”)

Alternative approach using signals and SceneTreeTimer

func wait_time_method3(seconds: float) → void:
var scene_tree = Engine.get_main_loop()
if scene_tree:
var timer = scene_tree.create_timer(seconds)
timer.connect(“timeout”, Callable(self, “_on_timer_timeout”))

func _on_timer_timeout() → void:
print(“Timer finished!”)

1 Like

Make sure to format your code pastes

1 Like