Variable is losing value when being passed to a new scene via Autoload

Godot Version



I’m trying to get an enemy to look at the player so I made a variable that has the player’s position:
var PlayerPos = self.position

The print_debug confirms the position is being saved. However, when I access the player position in the enemy scene it gets reset to 0, 0:
var PlayerPos = PlayerScript.PlayerPos

again the print_debug prints 0, 0.

The enemy ends up just walking to 0, 0 and getting stuck. Any ideas on how to fix? I’d be happy to give any more information if needed, or explain if my sleep deprived rambles don’t make sense.

Thanks in advance!

I think there might be a couple issues, like the autoload creates a separate instance of the player, or the position is passed by value, so it doesn’t “update” when the player moves…

Imo it would be better if you just created a new script to autoload. Just create a var player variable in it, then in the player’s _ready function put my_autoload_script.player = self. Then from the enemy’s script you can get the player’s position like: my_autoload_script.player.global_position

Sorry its been a while but im getting this error:
Invalid set index ‘Player’ (on base: ‘Node (’) with value of type ‘CharacterBody2D (’.

It means you don’t have a var Player variable in your load_script. Either create one, or if you already have one make sure it’s not misspelled or something

here’s my code:

extends Node

func _ready():
var Player

I checked the spelling, copy and pasted too. No luck :c

Oh that one you don’t have to put inside the _ready function, just simply

extends Node

var Player

ok, I’ll try that rq

that worked, thank you so much!

1 Like