Skip to content

Instantly share code, notes, and snippets.

@sam-yam
Created March 18, 2023 05:14
Show Gist options
  • Save sam-yam/4a5a0460f51e2f7c066cb644504f8de0 to your computer and use it in GitHub Desktop.
Save sam-yam/4a5a0460f51e2f7c066cb644504f8de0 to your computer and use it in GitHub Desktop.
Networked Singleton - Unity Netcode
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