Using variables from different scripts

Godot Version

Godot 4.4

Question

I’m making a 2D platformer and when you die to the spikes it will set a variable called dying to true. I want the script for my moving platforms to see that the dying variable is set to true and move faster but I don’t know how to access the variable in a different script.

There are several ways of doing this:

You could use a global script; see Project->Project Settings->Globals. If you have a global script named Foo with a variable bar, anything can access that via Foo.bar.

If you have a node path to something with an attached script, you can access the variables (and functions) in it with similar dot notation.

You can also do this with signals. I tend to avoid signals, personally; it’s really easy to wind up in a place where your flow control is incomprehensible, but they are intended to solve problems like this.

Is there a way to take a previously made script and make it global so for example, if Foo is attached to a node 2d already and then I make it global so bar, an existing variable can be accessed by Baz?

If you make something global I believe it just makes it a child at the root of the scene tree, so you probably don’t want to do that to an existing node elsewhere in the tree.

But if you know where the node is in the tree, you can access the things inside its script if you have a node path:

    $GameLevel/Player.got_spiked()
    for mob in $GameLevel/Mobs.get_children():
        mob.cackle()

Would this work if the Player is in a different scene?

As long as you can get a node path to it, it will work. You can use an absolute node path (that is, from the root) if you need to.

Thanks! I finally got it working.