+1 vote

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?

Godot version 3.4.4
in Engine by (203 points)

2 Answers

+3 votes
Best answer

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)
by (1,053 points)
selected by

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

Thank you. This will help a great deal.

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"]
[link3 - GitHub proposal + documentation]
[link4 - GitHub implementation]

+1 vote

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")
by (2,155 points)

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.

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.