how to use godot 4 setget?

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

how to use setget in godot 4?

in 3.5 i do like this

var state = null setget set_state
func set_state(new_state):
	previous_state = state
	state = new_state

if i do like this in godot 4. i will stack overflow

var state  = null :
	set(value): _set_state( value )

func _set_state( new_state ):
	previous_state = state
	state = new_state

and how to set state from same script?
3.5 we can self.state how about godot 4

:bust_in_silhouette: Reply From: Vickylance

Check this

https://forum.godotengine.org/114682/godot-4-setget-with-export

:bust_in_silhouette: Reply From: omggomb

If you want to use a single function as setter / getter you need to use:

var state = null : set = _set_state, get = _get_state

func _set_state(new_state):
    state = new_state

This way, there won’t be stack overflow when assigning to state inside the setter. The way you declare it is used for calculated properties that don’t need their own backing field.

2 Likes
:bust_in_silhouette: Reply From: TheYellowArchitect

While this works https://forum.godotengine.org/114682/godot-4-setget-with-export
I want to provide another answer for including static typing and custom set method, based on this docs page GDScript reference — Godot Engine (latest) documentation in English

3.x version:

export var sprite_offset : Vector2 = Vector2.ZERO setget set_sprite_offset

4.0 version:

@export var sprite_offset : Vector2 = Vector2.ZERO :
   set (value):
     set_sprite_offset(value)
  get:
    return sprite_offset

Edit: The above should give you an infinite loop!
Here is a working alternative

   @export var sprite_offset : Vector2 = Vector2.ZERO :
       set (value):
         sprite_offset = on_sprite_offset_change(value)
      get:
        return sprite_offset

func on_sprite_offset_change(value: Vector2) -> Vector2:
2 Likes