NewSingleton
Coding Style wiki
NewSingleton<T> is the plain C# class singleton base class of SingletonSystem (non-MonoBehaviour). It uses double-checked locking with lazy creation (new T()) to ensure the instance is created only once under multi-threading, suitable for data or logic manager classes that do not need to live on a GameObject.
| Namespace | OxGKit.SingletonSystem |
| Type | public class NewSingleton<T> where T : class, new() |
| Source | NewSingleton.cs |
using OxGKit.SingletonSystem;
Attention The generic constraint is where T : class, new() — type T must have a public parameterless constructor.
Reminder For manager classes that need the Unity lifecycle and scene objects, use MonoSingleton instead.
Quick Start
using OxGKit.SingletonSystem;
// Option 1: use by inheritance
public class ScoreManager : NewSingleton<ScoreManager>
{
public int score = 0;
public static void AddScore()
{
GetInstance().score++;
}
}
// Get the instance (lazy new T() creation)
var scoreManager = ScoreManager.GetInstance();
ScoreManager.AddScore();
// Option 2: without inheritance, use directly as a generic holder
public class ScoreService
{
public int score = 0;
}
NewSingleton<ScoreService>.GetInstance().score++;
Methods Overview
| Method | Description |
|---|---|
| GetInstance | Gets the singleton instance (lazy creation). |
| InitInstance | Initializes the singleton instance (same as calling GetInstance). |
| CheckInstanceExists | Checks if an instance exists. |
| DestroyInstance | Destroys the singleton instance (only clears the static reference). |
GetInstance
public static T GetInstance()
Gets the singleton instance; if no instance exists yet, double-checked locking ensures it is created only once with new T() under race conditions.
var scoreManager = ScoreManager.GetInstance();
InitInstance
public static void InitInstance()
Initializes the singleton instance (same as calling GetInstance); suitable for explicitly controlling the creation order during boot (warm-up).
ScoreManager.InitInstance();
CheckInstanceExists
public static bool CheckInstanceExists()
Checks if an instance exists (does not trigger creation).
if (ScoreManager.CheckInstanceExists())
ScoreManager.AddScore();
DestroyInstance
public static void DestroyInstance()
Destroys the singleton instance (only clears the static reference); if the old instance is still referenced elsewhere, that object is not released by this call — it is not a disposal mechanism.
ScoreManager.DestroyInstance();
Attention After clearing, the next GetInstance call creates a brand-new instance — the old instance's state is not preserved.