Advertisement
Guest User

Untitled

a guest
May 24th, 2018
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.88 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
  5. {
  6.     protected static T instance;
  7.  
  8.     /**
  9.        Returns the instance of this singleton.
  10.     */
  11.     public static T Instance
  12.     {
  13.         get
  14.         {
  15.             if(instance == null)
  16.             {
  17.                 instance = (T)FindObjectOfType(typeof(T));
  18.  
  19.                 if(instance == null)
  20.                 {
  21.                     //Try finding non-active scene object
  22.                     var objects = Resources.FindObjectsOfTypeAll<T>();
  23.                     if(objects.Length > 0)
  24.                         instance = objects[0];
  25.                 }
  26.                 if(instance == null)
  27.                 {
  28.                     Debug.LogError("An instance of " + typeof(T) +
  29.                        " is needed in the scene, but there is none.");
  30.  
  31.                 }
  32.             }
  33.  
  34.             return instance;
  35.         }
  36.     }
  37. }
  38.  
  39. // Example
  40.  
  41. public class GameManager : Singleton<GameManager>
  42. {
  43.     public int value = 1;
  44. }
  45.  
  46. // you can access value from anywhere with this
  47. GameManager.instance.value;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement