Do something every time an attribute change

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

I need to make something every time some Spatial.translation changes. The trivial solution would be to write that_function(Spatial.translation) inside all the functions in which Spatial.translation changes.

I neither want to use a _process(delta) or similar function because it is a turn-based game.


Have you looked at setters and getters to help with your problem?

Ertain | 2021-12-29 03:37

Could you give us more information on the operations you want to perform on each attribute modification

Midonk | 2021-12-29 12:51

It seems that it does not work for my case since Spatial.translation is already defined:
var translation : Vector3 setget changeTranlation
The member 'translation' alredy exists in a parent class

abelgutierrez99 | 2021-12-30 13:22

I want to change everytime Spatial.translation changes. This Spatials are voxels in a voxel-based game, so it is sometimes useful that = var2str(Spatial.translation).

This days I had an idea so I do not need this feature, but not tested yet. Otherwise, it would be a good idea to know how to solve a similar problem, noticing that setget does not work for already defined variables (built-in).

abelgutierrez99 | 2021-12-30 13:28

:bust_in_silhouette: Reply From: Gil-Koren

I’d use signals.
Create a signal:

signal translation_changed

in the ready function connect the signal to the script:


then, where you change your translatino you emit the signal:


and put your code to do stuff when it changed in a function called "_on_translatoin_changed", or how you decide to call it, just make sure its passed as the 3rd argument in the connect function.

That would work. My first idea was to create a function like
func change_translation(vector): translation = vector do something with the translation
but your option is also good. In fact, I prefer your solution :wink:


abelgutierrez99 | 2022-01-01 08:16