When I make a preload script in godot and put a variable in there, how do I call the variable in my other scripts?
Is there a special way to call the variable that I don't know or is there a better way to do it than preload scripts?
If you are preloading a script, e.g. const item = preload("res://scripts/item.gd")
it acts as a type. That is, you can declare variables as it, and make instances of it. The variables declared on the script exist on its instances:
const Item = preload("res://scripts/item.gd")
var my_item:Item
func _ready():
my_item = Item.new()
print(my_item.variable)
See Custom variable types and Classes and nodes. By the way, no, there are no static variables in Godot, see "static" on Keywords table.
You could be preloading a scene instead of a script. In that case you get a PackedScene
, similar rules apply. But you would be using the instance
method.
Instead of doing this, I suggest to give a class_name
to your script. Godot will recognize it and make it available everywhere. See Register scripts as classes.
Please note that this is different from accessing a variable defined on another node in the scene tree. If you are trying to access a variable defined in the script of another node in the scene tree, the use get_node
or similar to access the node, and then you can access the variable on it. See Understanding node paths.
If you need a global variable, what you want is an "singleton" autoload. You can set a scene to autoload in the "AutoLoad" tab in your project settings (select the scene path, give it a name, and click "Add"). They will be available on the scene tree regardless of the scene. They persist changes of scene.
Since autoloads are on the scene tree, you can use get_node
to access them. The path will "/root/"
followed by the name you gave it. For example:
onready var global_variables = get_node("/root/GlobalVariables")
func _ready():
print(global_variables.variable)
If you want to have access to one script from 1 or more different scripts, It is not a good way to use preload script. (at least in my opinion)
I prefer to make an script, global in the project and have access to that script from other scripts and nodes.
Now how to do that?
Open a new or a prefered scene.
On top menu, under project scroll, click on Project Settings.
On Project Settings, click on Autoload tab and add the script that you want to have access to from everyscript in the game and ofcourse add a fine Node Name to it.
Now based on that Node Name, you can have access to anything inside that global script.
For example, if this is my global script that I Autoloaded it as Global node name:
extends Node
var num: int = 5
I can have access to num variable from every other scripts like:
Global.num = 6
Make sure to take a look at the AutoLoad Documentation for more info.