VR Development Framework
v 1.0.0
 All Classes Namespaces Functions Variables Enumerations Enumerator Properties Events Pages
Singleton.cs
1 using System.Collections;
2 using System.Collections.Generic;
3 using UnityEngine;
4 
5 namespace AVR.Core {
6  /// <summary>
7  /// Basic class for Singleton classes. Sets a single, static instance of the class to the "Instance" property.
8  /// </summary>
9  /// <typeparam name="T"> Type of the Singleton. Should correspond to the class deriving from this. Example: class Example : Singleton&lt;Example&gt; </typeparam>
10  public abstract class Singleton<T> : AVR_Behaviour where T : AVR_Behaviour
11  {
12  public static T Instance
13  {
14  get
15  {
16  if (_Instance == null) _Instance = FindObjectOfType<T>();
17  return _Instance;
18  }
19  private set
20  {
21  _Instance = value;
22  }
23  }
24 
25  private static T _Instance;
26 
27  void Awake()
28  {
29  SetInstance();
30  }
31 
32  private void SetInstance()
33  {
34  if (_Instance != null && _Instance != this)
35  {
36  AVR_DevConsole.cwarn(this.name + " is marked as Singleton but another instance was found in the scene. Continuing to use old one.", this);
37  return;
38  }
39 
40  Instance = gameObject.GetComponent<T>();
41 
42  if (Instance == null)
43  {
44  AVR_DevConsole.cerror(this.name + " is marked as a Singleton of type " + typeof(T).ToString() + " but no component of this type was found!", this);
45  }
46 
47  DontDestroyOnLoad(this);
48  }
49 
50  public virtual void OnApplicationQuit()
51  {
52  Instance = null;
53  }
54  }
55 }
Monobehaviour but with an added URL button to a documentation page.
virtual void OnApplicationQuit()
Definition: Singleton.cs:50