Guest User

Simple Unity3D Singleton

a guest
Aug 4th, 2020
8,998
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.15 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. // by @kurtdekker - to make a simple Unity singleton that has no
  6. // predefined data associated with it, eg, a high score manager.
  7. //
  8. // To use: access with SingletonSimple.Instance
  9. //
  10. // To set up:
  11. //  - Copy this file (duplicate it)
  12. //  - rename class SingletonSimple to your own classname
  13. //  - rename CS file too
  14. //
  15. // DO NOT PUT THIS IN ANY SCENE; this code auto-instantiates itself once.
  16. //
  17. // I do not recommend subclassing unless you really know what you're doing.
  18.  
  19. public class SingletonSimple : MonoBehaviour
  20. {
  21.     // This is really the only blurb of code you need to implement a Unity singleton
  22.     private static SingletonSimple _Instance;
  23.     public static SingletonSimple Instance
  24.     {
  25.         get
  26.         {
  27.             if (!_Instance)
  28.             {
  29.                 _Instance = new GameObject().AddComponent<SingletonSimple>();
  30.                 // name it for easy recognition
  31.                 _Instance.name = _Instance.GetType().ToString();
  32.                 // mark root as DontDestroyOnLoad();
  33.                 DontDestroyOnLoad(_Instance.gameObject);
  34.             }
  35.             return _Instance;
  36.         }
  37.     }
  38.  
  39.     // implement your Awake, Start, Update, or other methods here...
  40. }
  41.  
Advertisement
Add Comment
Please, Sign In to add comment