0 votes

How do i make a custom signal that when the player click in a Area2D it emits a signal? I find kinda hard to understand signals is general, can someone also explain it to me its sintax?

in Engine by (19 points)

1 Answer

+1 vote

To create your own signal, let's call it my_signal, create a script that will handle the player clicking an Area2D. Suppose you call that function _on_area2d_click. This function should then call emit_signal("my_signal") to emit the custom signal my_signal along with any relavent parameters. For example, if your script counts the number of times the Area2D has been click using a variable clickCounter, then you could pass the counter via signaling as follows emit_signal("my_signal",clickCounter). You need to make sure your script has signal my_signal at the start of the script to define the custom signal can be emitted by this script

Now any script you want to do something when your signal occurs should have a handler function, let's call it _my_signal_handler. To connect to the handler, another script should connect to your signaling script as follows: `signalingScript.connect("mysignal",self,"mysignalhandler").

What is a signal
The signal system is just an implementation of the observer patter, a common programming design pattern. The idea is an observer may be interested in events, so it subscribes (connects in Godot) event publishers (in Godot, anything that emits a signal). This way your decoupling the observers/event-handlers from the event source. It makes your code cleaner if the event handlers don't have to worry about the details of how the signal was created, and the signal emitters don't have to worry about what is being done after the signal is create

by (574 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 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.