AR Design
UBC EML collab with UBC SALA - visualizing IoT data in AR
Singleton.cs
Go to the documentation of this file.
1 // Copyright (c) Microsoft Corporation. All rights reserved.
2 // Licensed under the MIT License. See LICENSE in the project root for license information.
3 
4 using UnityEngine;
5 
6 namespace HoloToolkit.Unity
7 {
14  public class Singleton<T> : MonoBehaviour where T : Singleton<T>
15  {
16  private static T instance;
17 
25  public static T Instance
26  {
27  get
28  {
29  if (!IsInitialized && searchForInstance)
30  {
31  searchForInstance = false;
32  T[] objects = FindObjectsOfType<T>();
33  if (objects.Length == 1)
34  {
35  instance = objects[0];
36  instance.gameObject.GetParentRoot().DontDestroyOnLoad();
37  }
38  else if (objects.Length > 1)
39  {
40  Debug.LogErrorFormat("Expected exactly 1 {0} but found {1}.", typeof(T).Name, objects.Length);
41  }
42  }
43  return instance;
44  }
45  }
46 
47  private static bool searchForInstance = true;
48 
49  public static void AssertIsInitialized()
50  {
51  Debug.Assert(IsInitialized, string.Format("The {0} singleton has not been initialized.", typeof(T).Name));
52  }
53 
57  public static bool IsInitialized
58  {
59  get
60  {
61  return instance != null;
62  }
63  }
64 
69  public static bool ConfirmInitialized()
70  {
71  T access = Instance;
72  return IsInitialized;
73  }
74 
81  protected virtual void Awake()
82  {
83  if (IsInitialized && instance != this)
84  {
85  if (Application.isEditor)
86  {
87  DestroyImmediate(this);
88  }
89  else
90  {
91  Destroy(this);
92  }
93 
94  Debug.LogErrorFormat("Trying to instantiate a second instance of singleton class {0}. Additional Instance was destroyed", GetType().Name);
95  }
96  else if (!IsInitialized)
97  {
98  instance = (T)this;
99  searchForInstance = false;
100  gameObject.GetParentRoot().DontDestroyOnLoad();
101  }
102  }
103 
110  protected virtual void OnDestroy()
111  {
112  if (instance == this)
113  {
114  instance = null;
115  searchForInstance = true;
116  }
117  }
118  }
119 }
static bool ConfirmInitialized()
Awake and OnEnable safe way to check if a Singleton is initialized.
Definition: Singleton.cs:69
virtual void OnDestroy()
Base OnDestroy method that destroys the Singleton&#39;s unique instance. Called by Unity when destroying ...
Definition: Singleton.cs:110
virtual void Awake()
Base Awake method that sets the Singleton&#39;s unique instance. Called by Unity when initializing a Mono...
Definition: Singleton.cs:81
static void AssertIsInitialized()
Definition: Singleton.cs:49
Singleton behaviour class, used for components that should only have one instance.
Definition: Singleton.cs:14