Use of AutoLoad in an optimal way

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Rensae

Hey there ! I’ve some trouble figuring out how to save variables with AutoLoad.
Let’s say I have a variable on a node “Player” named “health”
My “Global” script will do var Player1 : $[get_node].health

Then I’ll launch another instance, and I want to keep the health of this player in the same state. So, I’d do
var player1 = $"/root/Global".Player1 var health = player1.health

But there is a problem : If I try to print my var Player1 in my global script whenever I want to save it, it work
But when I switch scene, if I print my var health, it’ll return ‘null’

If there isn’t enough info just ask me, I’ll try to explain more, but I think that’s enough…?
Also, would the answer would be the same if I want to do that with String values ?
Thanks in advance !

:bust_in_silhouette: Reply From: jgodfrey

In your case, it seems that you’re attempting to use a singleton to retrieve information from one scene so that it can be accessed from some other scene. Rather than that, you probably want to store the information directly in the singleton, and then retrieve it in other scenes as necessary.

For example, in the autoload script

# Globals.gd
var playerHealth = 100

Then, in any other script:

Globals.playerHealth -= 10 # Subtract 10 from global player health
var myHealth = Globals.playerHealth # retrieve player health

So, rather than having the singleton retrieve information from other scripts dynamically, just directly store, retrieve, and update the information directly fromm the singleton.

Regarding your other question on string values. There’s nothing special there. Put the data in the singleton, and then update, modify it directly from any other script.

Thanks, that makes sense now :slight_smile:

Rensae | 2020-06-15 21:43