How can I refresh an Autoload?

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

So I am building a platformer, and I have an autoload script GlobalVar. In this script I have

var death_count = 0
var highest_level = 0
var current_level = 0

func _ready():
if current_level > highest_level:
highest_level = current_level

and when I load a new level I have it update the current level number. However, when I load a new level, it doesn’t actually update my highest level variable. So it stays at 0. Do I need to refresh the autoload, or is my if statement written wrong?

:bust_in_silhouette: Reply From: Bean_of_all_Beans

When you autoload a script as a global singleton, it is loaded once, at the beginning of when you first run your project (or game if exported). Because of this, your _ready function is only ever called once, and because you check if current_level is greater than highest_level during the _ready function, it will not check again. A possible way to fix this would be to make another function altogether, maybe naming it update_highest_score, and call it whenever you load a new level in your game.
Here’s an example I came up with:

func update_highest_score():
    if current_level > highest_level:
        highest_level = current_level
    current_level = 0

So whenever you load a new level, in whatever function you call to update the level to the next one, add a line to call update_highest_score. Hopefully this helped!

Thank you for the in depth explanation!! Your suggestion worked perfectly!

NoTheOtherMatt | 2020-08-27 16:39