+2 votes

I have a script that is extending the GridContainer, I am using the additional variable rows with appropriate setget applied, but I would like to use seget with the columns variable as well. Is it possible to add a setget onto an existing variable from an inherited class?

in Engine by (96 points)

1 Answer

+3 votes

Is it possible to add a setget onto an existing variable from an inherited class?

No. However, you can override the virtual _set- and _get-methods that are called after the built-in setter is called to achieve something very similar:

func _set(property, value):
    if property == "columns":
        print("SET: columns)

func _get(property):
    if property == "columns":
        print("GET: columns")

If you want to change the value of columns in _set, things become a bit tricky though as calling set() leads to an endless loop crashing the engine. After toying around a little, I came up with the following solution for that:

var modified = []

func _set(property, value):
    if property in modified:
        return false

    if property == "columns":
        set(property, value+2)
        return true

However, I cannot guarantee that this doesn't has unwanted side-effects.

Also keep in mind that setter functions are not called locally unless prefixed by self:

func _ready():
    columns = 5        # will _not_ trigger the setter
    self.columns = 5   # will trigger the setter
by (10,467 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 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.