0 votes

How I can create a callback mechanism or signal in class. Let's say I have created a class and I want to be able to execute a callback when some internal events happen.

I am wondering if something like that would be implemented for class. I suppose not as it is not a Node but only class:

class SimpleExample:
    signal my_signal

    func some_func():
        emit_signal(my_signal)

The callback that I wrote is also not ideal solution. For example:

class SimpleExample2:
    var my_callbacks = []

    func add_callback(fun_name):
        // check if not already added
        my_callbacks.append(fun_name)

    func some_func():
        // some interal calculations
        for fun in my_callbacks:
            call(fun)

But that will not work because my_callbacks are just strings so the call function do not know which node/object is the owner. It will simply try to run that name (fun) as the function.

in Engine by (58 points)

2 Answers

+1 vote
Best answer

For the callbacks to work, you also need to pass the object instance. You can see this format similar to the connect api in gdscript.

Inside the class you need to save the callback method and the instance in a dictionary format. The use call_deferred method to call it.

by (750 points)
selected by
0 votes

In 3.2 at least you can use the funcref() function, as the example on this post shows.

by (14 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.
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 webmaster@godotengine.org with your username.