Singleton value lost after restart

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

I have Global.gd (Singleton script) that goes like:

extends Node

var gbl = 0

Then I have a level script from where I call Global.gbl to store value in it. I do it this way:

if “something happens”:

Global.gbl = “some value”

Label.text = Global.gbl

Then I check the outcome, value is there, communication works as intended, but when I restart the level the Global.gbl is back to zero. What should be done to keep the renewed value after the restart?

What method are you using to restart the level?

JimArtificer | 2020-07-12 13:45

Three methods:

  1. I force-close the game and reopen it
  2. I have a button that calls:
  get_tree().reload_current_scene()
  1. I have a home button that calls the Menu Scene and I enter the same level again.

In all methods, the result is the same - the value starts as ZERO.

Do I need any function in Global.gd for it to operate as intended? Currently, all I have is:

 extends Node
 var gbl = 0

Suleymanov | 2020-07-12 13:57

Closing the game will clear the RAM that the singleton is allocated to. No surprise with how that is working. You’ll need to serialize some data and read it from disk to handle that case.

You could use the same method (save to disk, load scene, read from disk) to handle reloading the scene, but it’s not a method I would recommend.

Instead of reloading the current scene, save your level as a separate scene from the main game entry point and change/reload the child node. That should prevent the singleton from being instantiated multiple times.

JimArtificer | 2020-07-12 14:34

The level is indeed saved as a separate scene. And even when I launch the Level from the Menu scene the result remains the same. I use this script to launch the Level from Menu:

get_tree().change_scene("res://levels/track_01.tscn")

I even tried to start the Level scene with F6 (Play Scene) key, still no success.

It’s a bit frustrating why Singleton doesn’t operate the simple way when it has one job to do - store information. I intend to add variables to Singleton for 20 different levels as soon as I find out why information is lost at the restart.

Suleymanov | 2020-07-12 20:25