Topic was automatically imported from the old Question2Answer platform.
Asked By
OiKeTTLe
In my project, you go through different scenes, collecting emeralds. I have an emerald counter, but it resets every time the scene changes. I need to store the number of emeralds and update the label whenever the scene is changed. Help would be greatly appreciated.
This is the purpose of a singleton. It can contain data that you want to persist between scene changes.
See docs for details on creating and using singletons:
I’ve already set up a singleton. It automatically loads whenever the scene changes. However, i still don’t have a way to detect if the scene has changed or not. I don’t know what command to use to store the information from another variable and replace the information from said variable.
OiKeTTLe | 2021-02-23 00:34
Singletons do not reload when the scene changes.
I don’t know what you mean by “detect if the scene has changed”. The scene only changes when you tell it to with change_scene(). Whenever you do that, set the variable on the singleton.
I didn’t find an existing signal for this so I did it by routing all scene changes through an AutoLoad script instantiated as a singleton in Project Settings > AutoLoad:
using Godot;
using System;
using System.Diagnostics;
public class AutoLoad : Node {
static AutoLoad _Instance = null;
AutoLoad() {
Debug.Assert(_Instance == null);
_Instance = this;
}
// Use this exclusively instead of SceneTree method.
public static void ChangeScene(string name) {
Debug.Assert(_Instance != null);
_Instance.GetTree().ChangeScene(name);
_Instance.OnSceneLoaded(name);
}
void OnSceneLoaded(string name) {
// Respond to scene changes as needed here
}
}