AutoLoaded Scripts variables appear as null

Godot Version

3.6.1 stable

Question

For some reason, variables from the AutoLoad script appear as null when used outside of it. I have a signal emitted from the Player to the AutoLoad script called BroadCaster, which contains the player's position. The BroadCaster correctly prints the player's position, but when it's printed inside the Player or Enemy scripts, it appears as null, and its value is treated as such. Does anyone know a fix?




Autoload creates a new instance of your script/scene on the tree, it does not appear in editor and it does not know about the Player so you cannot connect signals to it through the eidtor. Check the “Remote” tab when running your game, you will see two "Broadcaster"s the global, next to Node2D and the one you are familiar with which is not a global, next to Player.

So how do I get the player’s position then? And I can’t quite undrestand why can’t any other node get the player’s position from BroadCaster when it does have it, but regardless thank you for the reply!

Hello!

If I understand this correctly, you want your enemies to know where your player is through an autoload.

I made this reply on another post, and at the end of it, I included my personal solution for sharing a reference of a node through an autoload:

And then in your enemy you can use something like this in your enemy’s movement function to access the player’s global position:

var player_pos: Vector2 = player.global_position

You probably don’t want to use a signal. Since the Broadcaster is global you can set it’s variables from the player directly. Instead of using emit_signal... directly set BroadCaster.Player_Position = position. And remove the duplicate “BroadCaster” node from your main scene.