Use Setget to signal when variable changes

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

Hello, I am very new to Godot and I am trying to make it so when my player’s health changes, it plays an animation. (for now im only worrying about any health change to play the animation).

My code is set so in my player script is a health variable

var playerHealth = 100 

And in the enemy script is a code that shoots a raycast and if it collides with the player, it changes the playerHealth to mins the damage

	if rayCast.is_colliding():
	var hit = rayCast.get_collider()
	if hit.is_in_group("Player"):
		target.playerHealth -= damage

While I could use a get_node command to make it play the animation from within the enemy script. it seems more ideal to make it play for when the health changes in the player script. and from some reading it seems setget is the best way to do this, But I am unsure of how to utilise it correctly still after reading up on it

:bust_in_silhouette: Reply From: timothybrentwood
var playerHealth = 100 setget set_player_health
var max_health = 100

func set_player_health(value):
	playerHealth = clamp(value, 0, max_health)
	# alternatively: playerHealth = value

Note that if you want the setter to be called when you set the playerHealth variable from inside the script you need to use self.playerHealth = some_value. This will be changed in godot 4.0