Set with Arrays

Godot Version

4.3

Question

How do I use set with arrays?

var organics: Array = [0]:
set(value):
organics[0] = value
materials_show.emit(“Organics”, “%OrganicsAmount”, organics )

This does not trigger when I modify organics[0]. Do I need some extra prefix or information for the set to work? Or does this fundamentally not work?

This doesn’t work because you’re not changing your current array for other array, you’re just modifying it and that will not trigger the setter. You need to create your custom function for it:

var my_array := [0]

func my_custom_setter(p_index: int, p_value) -> void:
	my_array[p_index] = p_value
	# Do whatever you need after

But what the objective of this var be an array? In your setter you only uses the index 0, so wouldn’t be more easier just use an int? (and in this case you would have a way to use the built-in setter)

1 Like

Okay, but how do I call the function every time the variable is changed? Or do I have to put the call in at every point this could happen? Seems clunky.

I started with an int but had to change to array because gdscript can not reference primitive types which I wanted to do.

Overall I’m trying to do something simple. Have some variables for resources and change them at different points in the game. But it turns out this is far harder than I thought or I’m just doing it wrong.
I’m still very new to this.

Have you tried to use an autoload node?

1 Like

@paul1
Your decision to use an Array for this purpose was flawed, try using the inner class instead as I suggested in the reply to your other post:

This way you can do you setter and emit the signal when the value of the class variable changes.

1 Like

Yeah, I will work on it over the next few days. It is something I have to learn eventually anyway.

Be prepared to face stupid questions about inner classes soon. :wink:

1 Like