How to create Custom Signals for when variable value changes

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

So I have a variable called direction. And I want a signal to emit whenever the value of this variable is changed.
Is that possible to do in Godot?

:bust_in_silhouette: Reply From: Gluon

Yes, it depends on your code as to the best way to do it. If you have a function where you are changing that variables value it would probably be best to emit the signal at the same time you change it. If you dont know in the function when it changes then you will need another variable to work that out for example:

func foobar:
   var pos = player.position
   if pos != poscheck:
      poscheck = pos
      emit_signal("example")

Thank you. Umm where do I call the foobar method? I dont want it in the process function since that defeats the purpose of using signals.

Skydome | 2022-06-07 17:40

:bust_in_silhouette: Reply From: Ninfur

You can add a setter function to the variable. A setter function is called everytime the variable is modified.

var direction setget set_direction

func set_direction(new_value):
    direction = new_value
    emit_signal("direction_changed", new_value)

I will add that if the object changing the var direction is the same one that owns the var direction (a common case, for example with a player scene), then the setter wont trigger. In that case you have to use self when changing the var, for example:

func change_dir():
    self.direction = new_value

Clarifing this, because it is a common pitfall when learning to use setters and getters, that I have personally fallen into

Pomelo | 2022-06-07 17:03

Thank you. This will help a great deal.

Skydome | 2022-06-07 17:41

Thanks @Pomelo for the self.member syntax trigger for Godot 3!

Looks like setget will be replaced in Godot 4 by Properties
[link1 - GitHub comment - Calinou memo]
[[link2 - Godot News - scroll down to “Properties”]][2]
[[link3 - GitHub proposal + documentation]][3]
[[link4 - GitHub implementation]][4]

gamepad_coder | 2022-12-05 04:25

1 Like