Heya. I've been trying for a long time to make global variables for my game but they just won't work. This is what I did:

  • I made a script that included the variables, I made that script into autorun, then I added some functions and constants to that script. Right when I go to use it, I use a variable on the other script I want to use the variable and then just use autoload and the path of the script.
    Now is when things get weird: the function and the constants do appear on the selection list and can be called, but variables won't.
    Could anyone please help me? Thank you so much!
  • xyz replied to this.

    Sure, thanks haha, I forgot.
    This is what I made. Btw, I missed up before: to get the path of the script I used preload
    This is the script for the global scene (Used in Autorune):

    extends Node
    
    var the_variable = 1
    const the_constant = 2
    func the_function():
    	pass
    
    Now, the script for the scene where that variable is used is the following:
    
    extends Node2D
    
    var global_script = preload("res://new_script.gd")
    
    func _ready():
    	print(global_script.the_variable)

    This is not the real code, just an exact replica but simplified and clearer (no nicknames I use to design my code xd). If it is made into Godot, it won't work as the script can only find the_function and the_constant.

    • xyz replied to this.

      oobiekanoobie
      If the script is set up as autoload you don't need to load or preload it manually. It will happen automatically. Doing var global_script = preload("res://new_script.gd") creates a reference to the script object which is not the same as reference to the scriptED object. The script object doesn't contain any properties of methods defined in its source code. You need an instance of the scriptED object. With autoload, that instance is created automatically by the engine.

      Okay, I think I understand your point.
      But then, how can I make the scripted object work on other scenes?
      Again, thank you so much for helping me 🙂

      • xyz replied to this.

        oobiekanoobie Autoloads are accessible in all scripts in any scene. That's the whole point of making them global. They are accessed via namespace you specify when creating an autoload in the project settings.

        Circled in red is the script you want to make global, and in blue is the name (namespace) you want to access it from any other script in the project

        So for example if the test_script.gd is:

        extends Node
        
        var value = 1
        
        func test():
        	print("It works!")

        Then from any other script you can simply do:

        my_global.test()
        my_global.value = 2

        This solved the whole issue. Thank you a lot for taking time to assist me, I hope you have a nice day! ^ v ^