Resetting a variable to its original value?

Godot Version

4.4

Question

Say I have a variable that is set by default to 1.0:
var my_variable = 1.0
And then I have another variable and I make it so that:
if my_other_variable = true: my_variable = 0.0
Now, as you may know, the moment “my_other_variable” resets back to false, “my_variable” stays at the last value (0.0 in this case) basically forever.
I know the first thing you may think of is to just type in:
else: my variable = 1.0
and sure, it works.
However, that would mean overriding the initial line (var my_variable = 1.0) anyway, which is not what I want.
I want the value of my variable to go back to its original pre-set value after the other variable goes back to false.
Is there any way I can achieve this?

Nope, variables do not store their initializing value separately, that would make every variable twice as large in-memory. You can create a const to hold values you find important, but shouldn’t change.

const VAR_DEFAULT: int = 123
var my_variable: int = VAR_DEFAULT

if true:
    my_variable = 0
else:
    my_variable = VAR_DEFAULT
2 Likes

Turns out, I can store the variable’s initial value within another variable without overriding anything, like this:
my_variable = 1.0
old_variable = my_variable
if my_other_variable = true: my_variable = 0.0
else: my_variable = old_variable
Which worked for me, fortunately. Thanks for anyone’s help, regardless…

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.