+1 vote

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 :)

asked Dec 15, 2019 in Projects by jayanthl (43 points)
edited Dec 15, 2019 by jayanthl

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

1 Answer

0 votes
Best answer

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);
}
answered May 8 by Zylann (26,033 points)
selected May 8 by jayanthl

Thank you very much!

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.