How to use setget in a array

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

How do I use setget in a array variable?

My variable was not an array, here is the old script:

var max_health = 0 setget set_max_health

func set_max_health(value):
		max_health = value

And the new one:

var max_health = [0, 1, 2] setget set_max_health
    
func set_max_health(value):
    	max_health = value

My question is, how am I supposed to change the function “set_max_health” in order to change correct “max_health” element?
I mean, the:

max_health = value

Thanks!

:bust_in_silhouette: Reply From: estebanmolca
var max_health = [0, 1, 2] setget set_max_health

func set_max_health(value):
		max_health= value
		
func _ready():
	self.max_health=[0,2,4]	
	self.max_health[0]=5
	print(max_health)

Is this behavior what you are looking for?
If you call the variable from outside the script, you don’t need to use self.

I’m sorry, that’s not what I meant.
What I mean, is how do I change the max_health in a specific index, because each player will have each own healths. Then if just one of them have this health changed I want to be able to change only his health inside this setget function.
There is a way to do this?
It was working when it wasn’t an array, but now I need to change a lot of things inside my code, and if I’m able to make this one work, I’ll be able to fix everything and it will work fine.

shoyguer | 2021-03-07 16:20

Just to understand well, the indices of the max_health array would be the health of different players?
Because with the line self.max_health [0] = 5 I am accessing the position 0 of the array (player 1) and changing its value (the other values do not change) and also using the setter function since I precede the self keyword. The setter function is executed, it cannot know what index changed, but it knows that some value in the array was changed.

estebanmolca | 2021-03-08 05:54