A lightweight Unity package for runtime singletons and attribute-driven auto singleton generation.
- Unity 2022.3 or newer
Create a singleton component by inheriting from MonoSingleton<T>.
using Sinsam.SingletonSystem;
[AutoSingleton]
public sealed class GameManager : MonoSingleton<GameManager>
{
protected override void InitializeSingleton()
{
// Initialize once here.
}
}Access it with:
GameManager.Instance;Instance automatically creates the singleton when it is missing, unless the singleton is blocked by a scene rule.
Add [AutoSingleton] to a concrete MonoSingleton<T> class.
[AutoSingleton(loadOnStart: true, createPrefab: true)]
public sealed class AudioManager : MonoSingleton<AudioManager>
{
}The editor generator scans attributed singleton types, creates prefabs under:
Assets/Resources/AutoSingletons
and writes the startup registry to:
Assets/Resources/SingletonRegistry.asset
The generator runs after script reload and can also be run manually from:
Tools > Singleton System > Generate Auto Singleton Registry
loadOnStart: if true, the generated or discovered prefab is added toSingletonRegistryand automatically instantiated when allowed by the current scene rules.createPrefab: if true, the editor creates or updates a prefab automatically. If false, the generator searches for an existing prefab underAssets/Resources/AutoSingletons.
SingletonRegistry can restrict a singleton to specific scenes. This is useful for managers such as BattleManager, StageManager, or DungeonManager that should exist only inside a gameplay context.
Open:
Assets/Resources/SingletonRegistry.asset
Then add an entry to Scene Rules:
Prefab: BattleManager
Allow All Scenes: false
Destroy When Scene Not Allowed: true
Scene Names:
- BattleScene
- BossBattleScene
With that setup:
BattleManageris created only when the active or loaded scene isBattleSceneorBossBattleScene.BattleManager.Instancereturnsnulland logs a warning outside registered scenes.- If a persistent
BattleManagerexists and the active scene changes to an unregistered scene,BattleManager.DestroyInstance()is called automatically. - If a
BattleManagerobject is placed directly in an unregistered scene, it is destroyed duringAwake().
Scene names can be either scene.name, such as BattleScene, or scene.path, such as Assets/Scenes/BattleScene.unity.
Rules are optional. If a singleton has no scene rule, it keeps the previous global behavior and can be created in any scene.
For non-MonoBehaviour classes:
using Sinsam.SingletonSystem;
public sealed class SaveService : Singleton<SaveService>
{
public SaveService()
{
}
}Access it with:
SaveService.Instance;