+1 vote

In my game I have local variables stored in the MainMenu scene and global variables that are stored in an AutoLoaded GlobalScript node. What I'm trying go do: Whenever the player goes from the Level scene to the MainMenu scene I want the local variables = the global variables and for the textboxes in the main menu to contain strings of the local variables.

I've gotten it to work with the following code:

points = GlobalScript.PointsToWin
$Base/OptionsContainer/PointsToWin/Points.text = str(points)

I have 5 variables to update this way, so I'd prefer to turn this into a function with three arguements that I can use so I don't repeat too much code. This is the function I came up with:

func load_value(local_var, global_var, textbox):
    local_var = global_var
    textbox.text = str(local_var)

load_value(points, GlobalScript.PointsToWin, $Base/OptionsContainer/PointsToWin/Points)

funcload() puts the correct value as a string in the textbox, but the local variable's values are still the defaults I've declared earlier in the script. I verified this by making the local variables export variables and checked them in the remote tree. What do I need to do in order for funcload() to do the same thing as the original code?

Godot version 3.3.2
in Engine by (31 points)

1 Answer

0 votes
Best answer

Hi,
variables like floats are passed by value (copied) and not by reference so in your load_value function, local_var starts with the value you passed but is local to the scope of the function (modifying it won't change your "true" local variable).
Notice how locally, local_var holds the right value and is put in the textbox, hence the behavior you noticed.

What you can do instead is provide the name of the variable and change it using set:

func load_value(local_var_name: String, global_var_value, textbox):
    set(local_var_name, global_var_value)
    textbox.text = str(global_var_value)
by (728 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.