Skip to content

Instantly share code, notes, and snippets.

@marutypes
Created July 1, 2023 19:46
Show Gist options
  • Save marutypes/fff14ec4f09c0953e18d0e277d257fb6 to your computer and use it in GitHub Desktop.
Save marutypes/fff14ec4f09c0953e18d0e277d257fb6 to your computer and use it in GitHub Desktop.
Unity Singleton base classes with networked variants
using Unity.Netcode;
using UnityEngine;
/// <summary>
/// Singleton base class for normal MonoBehaviours
/// </summary>
public class Singleton<T> : MonoBehaviour where T : Component
{
public static T Instance { get; private set; }
public virtual void Awake()
{
if (Instance == null)
{
Instance = this as T;
}
else
{
Destroy(gameObject);
}
}
}
/// <summary>
/// Singleton base class for when we need to make sure the object is not destroyed on scene change
/// </summary>
public class SingletonPersistent<T> : MonoBehaviour where T : Component
{
public static T Instance { get; private set; }
public virtual void Awake()
{
if (Instance == null)
{
Instance = this as T;
DontDestroyOnLoad(this);
}
else
{
Destroy(gameObject);
}
}
}
/// <summary>
/// Singleton base class for when we need Network primitives
/// </summary>
public class SingletonNetwork<T> : NetworkBehaviour where T : Component
{
public static T Instance { get; private set; }
public virtual void Awake()
{
if (Instance == null)
{
Instance = this as T;
}
else
{
Destroy(gameObject);
}
}
}
/// <summary>
/// Singleton base class for when we need to make sure the object is not destroyed on scene change AND need Network primitives
/// </summary>
public class SingletonNetworkPersistent<T> : NetworkBehaviour where T : Component
{
public static T Instance { get; private set; }
public virtual void Awake()
{
if (Instance == null)
{
Instance = this as T;
DontDestroyOnLoad(this);
}
else
{
Destroy(gameObject);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment