0 votes

I created a global variable, but during the game I don't want that the variable became negative. For now I do this:

If variable > 0
variable -= 1

But it is becoming boring to do with all the items and stuffs in game...

in Engine by (55 points)

1 Answer

0 votes
Best answer

You can create a setter function for the variable. In that function, you can pre-process the value before accepting, rejecting, or changing it.

So, for example, in your global script (Globals.gd in this case):

# set up the var and define a setter function
var pos_var = 1 setget pos_var_set

# here, only accept the value if it's positive. Otherwise, set it to zero.
func pos_var_set(new_val):
   if new_val > 0:
       pos_var = new_val
   else:
       pos_var = 0

Now, from some other script, you won't be able to set the var to a negative value

func _ready():
    Globals.pos_var = 2
    print(Globals.pos_var)
    Globals.pos_var -= 10
    print(Globals.pos_var)
    Globals.pos_var = -100
    print(Globals.pos_var)

See the docs here for details:

https://docs.godotengine.org/en/stable/getting_started/scripting/gdscript/gdscript_basics.html?highlight=setget#setters-getters

by (10,932 points)
selected by
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.