Skip to content

Instantly share code, notes, and snippets.

@Fenikkel
Last active May 16, 2025 15:42
Show Gist options
  • Save Fenikkel/046005a2d1dc454fd0c0c965371cbe87 to your computer and use it in GitHub Desktop.
Save Fenikkel/046005a2d1dc454fd0c0c965371cbe87 to your computer and use it in GitHub Desktop.
Static MonoBehaviour

Static MonoBehaviour

 

Notes

Simple tu use and foolproof. It uses abstraction to make it almost invisible on your code and easy to reuse it.

 

Usage

  1. Have the script in your project

  2. Call MonoBehaviour dependent functions with Static.MonoBehaviour:

    Static.MonoBehaviour.StartCoroutine(iEnumerator);

 

Compatibility

  • Any Unity version
  • Any pipeline (Build-in, URP, HDRP, etc)

 

Support

⭐ Star if you like it
❤️️ Follow me for more

using UnityEngine;
public class Static : MonoBehaviour
{
static MonoBehaviour s_MonoBehaviour;
public static MonoBehaviour MonoBehaviour { get { return s_MonoBehaviour; } }
#region Singleton
private static Static _Instance = null; // This value is shared for all instances
public static Static Instance
{
get
{
return _Instance;
}
}
private void CheckSingleton()
{
if (_Instance != null && _Instance != this) //If the instance we got is from another
{
Destroy(this.gameObject);
return;
}
else
{
_Instance = this;
}
this.transform.parent = null; //Unparent for the sake of the DontDestroyOnLoad
DontDestroyOnLoad(this.gameObject);
}
#endregion
private void Awake()
{
CheckSingleton(); // Doble check in case there are multiple instances in the scene
s_MonoBehaviour = GetComponent<MonoBehaviour>();
}
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterSceneLoad)] // Runs after a scene gets loaded (can change to before)
public static void StartThis()
{
if (_Instance != null)
{
Debug.LogWarning($"<b>{_Instance.name}</b> is going to be unparented and moved into the \"DontDestroyOnLoad\" area. Check that you don't have any attached components.");
return;
}
Debug.Log($"Initializing <b>{nameof(Static)}</b>");
new GameObject(nameof(Static), typeof(Static));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment