How to use timer and yield in c++ gdnative ?

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

How to use timer and yield in c++ gdnative ?

I have the below code

Timer* timer = Timer()._new();
timer->set_wait_time(3);
add_child(timer);
Godot::print("Timer started");
timer->start();
std::this_thread::yield();
Godot::print("Timer ended");;

How can i yield for timeout signal in c++ ?
The timer is not working and the execution is not delayed!

Thank you in advance :slight_smile:

Hello there, any update on how to do this afterwards? Thank you

omomthings | 2020-03-13 06:30

:bust_in_silhouette: Reply From: Zylann

Several notes about your code:

Timer* timer = Timer()._new();

This is not the right way to create a new node instance. Timer() creates an instance on the stack which I believe is not really supported by Godot objects. Then you call _new() which is a static function. Static function don’t require an instance to be called so the constructor call before is unnecessary.

Usually in C++ we use new Timer() to create a new instance on the heap, however the Godot C++ bindings use _new() instead for reasons I don’t remember:

Timer *timer = Timer::_new();

Then, about yielding:

std::this_thread::yield();

yield is something specific to GDScript. It is not directly supported in C++. std::this_thread::yield() does something very different which is not what Godot yields do.

If you want to execute code when the timer emits the timeout signal, you can’t do it in the same function, you have to make another one which you will use as signal handler:

void YourClass::on_timeout() {
	Godot::print("Timer ended")
}

You have to register that function, so then you can connect it to the timer:

timer->connect("timeout", this, "on_timeout");

This way, on_timeout should be called when the timer emits the timeout signal.
Recap of the code:

void YourClass::some_function() {
	//...

	Timer* timer = Timer()._new();
	timer->set_wait_time(3);
	add_child(timer);
	Godot::print("Timer started");
	timer->start();
}

void YourClass::on_timeout() {
	Godot::print("Timer ended")
}

void YourClass::_register_methods() {
	//...

	register_method("on_timeout", &YourClass::on_timeout);
}

Thank you very much!

jayanthl | 2020-05-08 15:42