Advertisement
Guest User

Simple Unity3D Singleton (with Data)

a guest
Aug 4th, 2020
4,783
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.61 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. // by @kurtdekker - to make a Unity singleton that has some
  6. // prefab-stored, data associated with it, eg a music manager
  7. //
  8. // To use: access with SingletonViaPrefab.Instance
  9. //
  10. // To set up:
  11. //  - Copy this file (duplicate it)
  12. //  - rename class SingletonViaPrefab to your own classname
  13. //  - rename CS file too
  14. //  - create the prefab asset associated with this singleton
  15. //      NOTE: read docs on Resources.Load() for where it must exist!!
  16. //
  17. // DO NOT DRAG THE PREFAB INTO A SCENE! THIS CODE AUTO-INSTANTIATES IT!
  18. //
  19. // I do not recommend subclassing unless you really know what you're doing.
  20.  
  21. public class SingletonViaPrefab : MonoBehaviour
  22. {
  23.     // This is really the only blurb of code you need to implement a Unity singleton
  24.     private static SingletonViaPrefab _Instance;
  25.     public static SingletonViaPrefab Instance
  26.     {
  27.         get
  28.         {
  29.             if (!_Instance)
  30.             {
  31.                 // NOTE: read docs to see directory requirements for Resources.Load!
  32.                 var prefab = Resources.Load<GameObject>("PathToYourSingletonViaPrefab");
  33.                 // create the prefab in your scene
  34.                 var inScene = Instantiate<GameObject>(prefab);
  35.                 // try find the instance inside the prefab
  36.                 _Instance = inScene.GetComponentInChildren<SingletonViaPrefab>();
  37.                 // guess there isn't one, add one
  38.                 if (!_Instance) _Instance = inScene.AddComponent<SingletonViaPrefab>();
  39.                 // mark root as DontDestroyOnLoad();
  40.                 DontDestroyOnLoad(_Instance.transform.root.gameObject);
  41.             }
  42.             return _Instance;
  43.         }
  44.     }
  45.  
  46.     // implement your Awake, Start, Update, or other methods here...
  47. }
  48.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement