0 votes

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.

Godot version 3.2.3
in Engine by (103 points)

3 Answers

+1 vote

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:
https://docs.godotengine.org/en/3.2/getting_started/step_by_step/singletons_autoload.html

by (21,309 points)

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.

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.

SingletonName.variable = value
0 votes

You can write a scene changer script that emits a signal or use my sophisticated, overengineered one:
https://github.com/hilfazer/Projects/tree/master/Godot/SceneSwitcher
Add it to autoloads, connect to its sceneSetAsCurrent() signal and use it for changing scenes.

My script also handles passing parameters to the new current scene.

by (2,294 points)
0 votes

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
    }
}
by (78 points)
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.