Created
March 18, 2023 05:14
-
-
Save sam-yam/4a5a0460f51e2f7c066cb644504f8de0 to your computer and use it in GitHub Desktop.
Networked Singleton - Unity Netcode
This file contains hidden or 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; | |
/* | |
Generic classes for the use of singleton | |
there are 3 types: | |
- MonoBehaviour -> for the use of singleton to normal MonoBehaviours | |
- NetworkBehaviour -> for the use of singleton that uses the NetworkBehaviours | |
- Persistent -> when we need to make sure the object is not destroyed during the session | |
*/ | |
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); | |
} | |
} | |
} | |
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); | |
} | |
} | |
} | |
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); | |
} | |
} | |
} | |
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