Node not found: "AnimationPlayer" (relative to "/root/Player")

Godot Version

Godot 4.2.1

Question

So I tried to add Gui for my 2d game, so I created a canvaslayer and some stuff inside and then I tried to access the variables I have in my player script. And to do that I put my player script to Autoload. And now my player script has this error:

player.tres.gd:13 @ _ready(): Node not found: “AnimationPlayer” (relative to “/root/Player”).

Adding a script to autoload creates a new node with that script. (You can’t see it in your scene tree, autoload nodes are “above” your root node, so to say). So if you add your player script to autoload, you’re not accessing the variables on your actual player character, but from another instance.
And since it’s a different node, the node paths in the script are wrong too, that’s why it doesn’t find the animation player. At least I think so…

What you can do is create a new autoload script, “Global” for example, and add a variable named var player.
Then you can put this in your player’s _ready() function.

func _ready():
    Global.player = self

And after that Global.player will refer to the actual palyer character and you can access the player from anywhere

1 Like

Ok so I have the Global thing, but now in my script for my gui if I want to access the variables in the player script. What do I have to write to access the variables in my script now

You can access any variable in the player’s script like:
Global.player.your_variable
For example if your player script has a var health = 100 variable:
Global.player.health

I get the error invalid index ‘damage’ (on base: ‘Nil’).

I don’t know, if you put Global.player = self in your player script’s _ready() then it should work. Make sure you’re not trying to access it before the player node is ready.

I have Global.player = self in the ready function but it still doesnt work