Created
July 1, 2023 19:46
-
-
Save marutypes/fff14ec4f09c0953e18d0e277d257fb6 to your computer and use it in GitHub Desktop.
Unity Singleton base classes with networked variants
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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