Topic was automatically imported from the old Question2Answer platform.
Asked By
abodactyl
When trying to assign variables in a class, they’re returning as null or blank later on, despite being confirmed to be assigned. Here’s an example, where kx is a string with value “0001”:
var key: String
...
func my_function(kx: String):
print(kx) # prints "0001"
key = kx
print(key) # prints "0001"
When querying this value in _physics_process(), it returns as a blank string. I’ve observed similar results when assigning other types of variables.
I’ve probably missed something stupid, but nonetheless does anyone know the issue?
Well I am not sure we have enough information here but there are a few possibilities.
This is a function where you are passing a string. If you pass the string once to the function it only keeps that value while running that function. As soon as the function ends the variable would return to Null. If you wanted it to remain then you would need to set the variable as having a default in the function or else set it as a global variable.
When you start up a new instance of a node then it will not keep the value you assigned to a different node. So for example if you have node enemy and you make several enemies then setting it in enemy 1 will not keep the same value in enemy 2.
You are reassigning the value somewhere else
Thank you! I have a feeling it’s the first one, not very strong on my GDScript. How would I go about making the variable global?
abodactyl | 2022-11-20 21:03
Well to be honest I suspect you can do what you want very simply. Try setting up a test project, create one script on a node (I will call it Global in this example), go into project>project settings>autoload and load that script as an autoload. In that script simply have the following
onready var Example_Var = ""
func _ready():
pass
then create a second node and in it put something like this
func _process():
print(Global.Example_Var)
func buttonExample():
if Input.is_action_just_pressed("ui_select") :
Global.Example_Var = Global.Example_Var + "a"
assuming ui_select is set to space for you (which should be the standard) you should see the above continuing to print the var in your Global node and adding an a each time you select space. As you can see you can directly change the variable, no need to add a function.