+1 vote

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?

Godot version 3.2.3
in Engine by (19 points)

1 Answer

0 votes

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.

by (265 points)
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 webmaster@godotengine.org with your username.