Making array of variables, then getting one of them and changing its value.

Godot Version

4.7.2.stable

Question

Hello!
I am still new to Godot and I am not programist at all. Just trying my best to make it work.

I have int variables, they are 0 by default. By playing you can get some of them at 1, or maybe even 4 value. And here is the problem.

I want to make an array with those variables that are above 0. Then, pick random one form the array and clear the value to 0.

I tried to do so, but I am stuck for now…

var first = 0 
var second = 0 
var third = 0
var fourth = 0
var fifth = 0

var current_variables : Array

func on_variables_changed():
 current_variables.clear()
 if first > 0:
    current_variables.append(first)
 if second > 0:
    current_variables.append(second)
 if third > 0:
    current_variables.append(third)
 if fourth > 0:
    current_variables.append(fourth)
 if fifth > 0:
    current_variables.append(fifth)


func on_clearing_variable():
 var clearig_one = current_variables.pick_random().name()
 clearing_one = 0

You can just do

func change_value(index: int, value: int):

current_variables[index] = value

And when you change a value, instead of doing e.g. “first = 3, on_values_changed()”, you just do change_value(index, value)

Index and value can be 1,4 or whatever you want. You dont have to name the values. The function that receives them will itself convert them into the variables index and value.

So change_value(0,2) would change the value of “first” to 2. But you dont need a long list of variables or a match statement.

If you store your data in an Array then you don’t need first/second etc. pick_random will give you a value back, but no information as where that value came from, you need to get a random index.

var current_variables: Array = [0, 0, 0, 0, 0]

func get_and_clear_value() -> float:
    var random_index := randi_range(0, current_variables.size())
    # Copy the randomly selected value
    var random_value: float = current_variables[random_index]
    # Clear the original value from the array
    current_variables[random_index] = 0
    return random_value