+9 votes

How can I execute a function after a time delay without having to create an Animation?
For example, call Node.queue_free after 2 seconds?

In Unity this is done with Invoke(callback, seconds).

asked Mar 19, 2016 in Engine by Zylann (25,912 points)
edited Mar 19, 2016 by Zylann

3 Answers

+9 votes
Best answer

One idea would be to make a variable called time_left, and decrement it in _fixed_process by delta. After it is less than zero, call the function you want.

Another way would be to use a Timer node, and its timeout signal:

timer.connect("timeout", self, "queue_free")

A third way would be to use the Tween node, which has some quite versatile uses...

tween.interpolate_callback(self, 1, "queue_free")
answered Mar 19, 2016 by Bojidar Marinov (1,538 points)
selected Mar 19, 2016 by Zylann

Ok, at the moment I use a custom timer in a the _process() method.
But because it's a bit long to write, I also thought about a manager like this:

some_global_script.execute_later(self, "my_callback", 2)

Well, you can easily set this up with the Tween approach.

Yes, but it involves the creation of a node anyways.

Since global (autoload) scripts are also nodes, it wouldn't be a big deal to addchild(mynewshinysubnode)... except that you would have to refer to them by variable, and not by name.

It's just a matter of saving a node, in case I'm going to have many instances of the scene requesting the invoke_later(). But at the moment I don't care that much, so I'll take the option requiring the less work :)

0 votes

There's a couple ways this can be done.

1) You can add a timer, and run the function when it times out.
2) you can set up a couple variables of your own to hold the time and a value to check against time out and make your own accumulator (either in frames or by accumulating delta)

answered Mar 19, 2016 by dc1a0 (215 points)
+6 votes
yield(get_tree().create_timer(1.0), "timeout")
answered May 28, 2019 by heston_in_mtl (38 points)
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 How to use this Q&A? before posting your first questions.