Godot Offers a way to emit messages from one object to another through the use of signals.
To create a signal, you need to create an observer class and a subject class.
A subject class emits a signal to the observer class. In contrast, the observer class performs an action once it has received a call/signal from the subject class.
In a sense, the subject class is expected to fire a signal; an observer needs to subscribe to a subject.
Both the subject class and the emitter class must be present on the scene tree. That means both classes need to be a node on the scene tree.
To create a Subject class, use the signal
keyword.
signal <signal name>
To send signals to observables, you need to call the emit_signal
method.
The emitted signal has one mandatory argument and optional argument if you want to pass data to the observables.
emit_signal(<signal name>, <optional data to pass>)
To create an observable, you need to create a variable instance of the Node on the
scene tree, followed by calling the signals connect
method.
The connect
method takes in 3 mandatory arguments and additional optional arguments
if you want to pass data to the observables.
connect(<signal name>, <node you want to call function in>, <function to call>)
Let’s take a look at a complete example:
# Subect Class
# Name in Scene: Player
# node Type: Sprite
extends Sprite
signal healthChanged # create the signal called healthChanged
var check: int = 0
var playerHealth: int = 100
func _process(deltaTime):
if check < 1:
check = check + 1
changeHealth(-100)
func changeHealth(value):
playerHealth = playerHealth + value
emit_signal("healthChanged", playerHealth) # Emit the signal to observables
In this example, we have a Node on the Scene tree called Player
, and we would like to create a signal that emits every time the players' health has changed.
On top of that, we pass the value of the players' current health to the observables.
In this case, we want to know when the method called changeHealth(value)
has been called.
The Player Node is considered the subject class.
# Oberver Class
# Name in Scene: Health
# node Type: Node2D
extends Node2D
onready var PlayerNode = get_node('Player')
func _ready():
PlayerNode.connect("healthChanged", self, "doSomething") # Connect to signal
func doSomething(playerHealth):
print('We changed value of health to: ', playerHealth)
The script above is attached to the scene in a Node called Health
.
You create an instance to the Player node with onready var PlayerNode = get_node('Player')
.
Then you connect to its signal with PlayerNode.connect("healthChanged", self, "doSomething")
.
Signals | Godot GDScript Tutorial | Ep 25 video & article by Godot Tutorials is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License .