Is it possible to create a generic attribute setter

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

I have multiple attributes that I want to perform exactly the same procedure on their setters.

For example, I have:

var foo : float setget _set_foo
var bar : float setget _set_bar

func _set_foo(value : float) -> void:
    foo = _some_function(value)

func _set_bar(value : float) -> void:
    bar = _some_function(value)

Let’s say I have N different variables, and they all would have this exact same setter.

Is there a way to make it a generic setter instead, so that I can write it only once and use it for all variables?

:bust_in_silhouette: Reply From: gnumaru

You could try something this:

func _set(n, v):
	var backing = '_'+n
	if backing in self:
		set(backing, my_func(v))
		return true
func my_func(v):
	pass # write your logic here

Then you use it like this

var _property

func _ready():
	self.property = 123.456
	
func _set(n, v):
	var backing = '_'+n
	if backing in self:
		set(backing, my_func(v))
		return true
		
func my_func(v):
	return '%s'%v

So you will declare class fields with an underscore, but you will set them without the underscore.