Skip to content

Instantly share code, notes, and snippets.

@sonnguyen9800
Created June 14, 2024 00:11
Show Gist options
  • Save sonnguyen9800/be783bad8e252eb5a38be8e4c3461c1b to your computer and use it in GitHub Desktop.
Save sonnguyen9800/be783bad8e252eb5a38be8e4c3461c1b to your computer and use it in GitHub Desktop.
GodotSingleton
using Godot;
using System;
public abstract partial class BaseSingleton<T> : Node where T : Node
{
private static T _instance = null;
public static T Instance => _instance;
// Called when the node enters the scene tree for the first time.
public override void _Ready()
{
}
// Called every frame. 'delta' is the elapsed time since the previous frame.
public override void _Process(double delta)
{
}
public override void _EnterTree()
{
if (_instance != null)
{
this.QueueFree(); // The Singletone is already loaded, kill this instance
GD.PrintErr("This singleton already loaded. Remove this");
}
_instance = this as T;
}
}
@sonnguyen9800
Copy link
Author

Sample Usage:

public partial class Manager : BaseSingleton<Manager> {

    public void DoSomething(){
        GD.Print("Do Something Here");
    }
}
// Manager.Instance.DoSomething()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment