Skip to content

Instantly share code, notes, and snippets.

@caglarenes
Created October 25, 2024 14:00
Show Gist options
  • Save caglarenes/720c4f6a13f78f29cf501d3b70656360 to your computer and use it in GitHub Desktop.
Save caglarenes/720c4f6a13f78f29cf501d3b70656360 to your computer and use it in GitHub Desktop.
Unity Singleton Desing Pattern Helper Scripts
using UnityEngine;
public class ScopedSingleton<T> : MonoBehaviour where T : MonoBehaviour
{
static T m_instance;
public static T Instance
{
get
{
if (m_instance == null)
{
Debug.LogWarning($"SCOPED SINGLETON {typeof(T).FullName} SHOULD NOT BE EMPTY!");
m_instance = FindAnyObjectByType<T>();
if (m_instance == null)
{
Debug.LogWarning($"SCOPED SINGLETON {typeof(T).FullName} SHOULD NOT BE CREATE WITH CONSTRUCTOR!");
GameObject singleton = new(typeof(T).Name);
m_instance = singleton.AddComponent<T>();
}
}
return m_instance;
}
}
public virtual void Awake()
{
if (m_instance == null)
{
m_instance = this as T;
}
else
{
Debug.LogWarning($"THERE ARE 2 COPY OF {m_instance.GetType().Name}!");
if (m_instance != this as T)
{
Destroy(gameObject);
}
else
{
Debug.LogWarning($"SCOPED SINGLETON {m_instance.GetType().Name} CALLING BEFORE ITS OWN AWAKE CALL");
}
}
}
}
using UnityEngine;
public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{
static T m_instance;
public static T Instance
{
get
{
if (m_instance == null)
{
Debug.LogWarning($"SINGLETON {typeof(T).FullName} SHOULD NOT BE EMPTY!");
m_instance = FindAnyObjectByType<T>();
if (m_instance == null)
{
Debug.LogWarning($"SINGLETON {typeof(T).FullName} SHOULD NOT BE CREATE WITH CONSTRUCTOR!");
GameObject singleton = new(typeof(T).Name);
m_instance = singleton.AddComponent<T>();
}
}
return m_instance;
}
}
public virtual void Awake()
{
if (m_instance == null)
{
m_instance = this as T;
if (TryGetComponent(out RectTransform _)) return;
DontDestroyOnLoad(gameObject);
}
else
{
Debug.LogWarning($"THERE ARE 2 COPY OF {m_instance.GetType().Name}!");
if (m_instance != this as T)
{
Destroy(gameObject);
}
else
{
Debug.LogWarning($"SINGLETON {m_instance.GetType().Name} CALLING BEFORE ITS OWN AWAKE CALL");
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment