+1 vote

I'm trying to do an experiment where a line of code is executed and then few seconds (e.g. 3 seconds) later, the next line of code will run. This is the code I used for this experiment.

extends Node

func _ready():
    print("Process ready!\n")


func _process(delta):
    var wait_time

    print("Process ongoing...\n")

    wait_time = 10000000

    while wait_time > 0:
        wait_time -= 1

    print("Done!")

    get_tree().quit() 

However, the code didn't work like I expected. The scene window just stayed there for a while and the 3 lines of text appeared on the output window almost simultaneously before the scene window closed a spilt second later. Is there anything wrong with the code? And is there a better way to achieve this?

in Engine by (25 points)

1 Answer

+2 votes
Best answer

Hello!

Welcome to the Godot forums.

I would expect that to all happen quickly - ready() is called as soon as the object is ready to process, then _process(delta) is called every frame so the next line will appear 1 frame later. The the third line will print after you count to 10 milliion (which does not take long - on my computer that is 490ms)

The approach you are taking will be very inefficient - you are asking your CPU to count to 10 million as quickly as it can. That will max out your CPU until it is complete. The length of the delay will vary depending on how fast your computer is, so that will not give you a predictable delay. Also, when you run that inside _process you are asking Godot to do that every frame - maybe 30 or 60 times a second. Forcing the CPU to 100% is not good practice :-)

Much better to use a Timer. Documentation is here. The principle of the Timer is that you setup the timer, then it runs for a configurable time (using minimal CPU) and then calls a configurable function when it is done. Check out the docs for details.

You can add timers in the scene tree. There is a nice tutorial here or you can find many more online

Or, a shortcut to add an inline timer is:

yield(get_tree().create_timer(3), "timeout")

This line pauses your code for 3 seconds and lets Godot do something else. When the timer is done, it comes back to where it was.

by (541 points)
selected by
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.