All Questions

Community

O
Rabbit One

about setget functionality and advantages

I'm trying to understand the advantages of using setget in code.

You've used this piece of code:

.
.
.
var controls: = KBD_MOUSE setget set_controls

func _input(event):
	if event is InputEventJoypadButton or event is InputEventJoypadMotion:
		if controls == KBD_MOUSE:
			self.controls = GAMEPAD
	elif event is InputEventMouse and controls == GAMEPAD:
		self.controls = KBD_MOUSE

func set_controls(value: int) -> void:
	controls = value
	emit_signal("controls_changed")

Is it possible to arrive to the same result using this code?

.
.
.
var controls: = KBD_MOUSE

func _input(event):
	if event is InputEventJoypadButton or event is InputEventJoypadMotion:
		if controls == KBD_MOUSE:
			self.controls = GAMEPAD
			set_controls(1)
	elif event is InputEventMouse and controls == GAMEPAD:
		self.controls = KBD_MOUSE
		set_controls(0)

func set_controls(value: int) -> void:
	controls = value
	emit_signal("controls_changed")

So, what is the advantage of using setget? Thanks!

  • Nathan Lovato replied
    Solution

    When you use a setter function, any other class or script that changes controls will have it go through the setter. While in your example, assigning a new value to the controls and calling set_controls do two different things.

    In general, you want to use a setter function whenever you want to process a value assigned to a variable in some way. For example

    var max_health := 100.0
    var health := max_health setget set_health
    
    func set_health(value: float) -> void:
    	health = clamp(value, 0.0, max_health)
    	if is_equal_approx(health, 0.0):
    		emit_signal("health_depleted")