Unity SDK Docs 1.5.0-beta.6
Loading...
Searching...
No Matches
Singleton.cs
1/*
2 * Copyright (C) 2020-2023 Tilt Five, Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16using System.Collections;
17using System.Collections.Generic;
18using UnityEngine;
19
20namespace TiltFive
21{
22 public class Singleton<T> where T : new()
23 {
24 private static readonly T instance = new T();
25
26 // Explicit static constructor to tell C# compiler
27 // not to mark type as beforefieldinit
28 static Singleton()
29 {
30 }
31
32 protected Singleton()
33 {
34 }
35
36 protected static T Instance
37 {
38 get
39 {
40 return instance;
41 }
42 }
43 }
44
45 public class SingletonComponent<T> : MonoBehaviour where T : UnityEngine.MonoBehaviour
46 {
47 private static T s_Instance = null;
48 public static T Instance
49 {
50 get
51 {
52 if( s_Instance != null )
53 {
54 return s_Instance;
55 }
56
57 T[] instances = Resources.FindObjectsOfTypeAll<T>();
58 if( instances != null )
59 {
60
61 // find the one that is actually in the scene (and not the editor)
62 for( int i = 0; i < instances.Length; ++i )
63 {
64 T instance = instances[ i ];
65 if( instance == null )
66 {
67 continue;
68 }
69
70 if( instance.hideFlags != HideFlags.None )
71 {
72 continue;
73 }
74
75 // avoid selecting component attached to a prefab asset that isn't in scene
76 if( string.IsNullOrEmpty(instance.gameObject.scene.name) )
77 {
78 continue;
79 }
80
81 s_Instance = instance;
82
83 //We can't use DontDestroyOnLoad on objects that aren't root objects. (i.e. objects that have a parent)
84 if(s_Instance.gameObject.transform.parent == null && Application.isPlaying)
85 {
86 DontDestroyOnLoad( s_Instance );
87 }
88 break;
89 }
90 }
91
92
93 if(s_Instance == null
94 // Don't automatically generate a new instance if the application isn't playing
95 // (i.e. we're in the editor with the game stopped)
96 && Application.isPlaying)
97 {
98 string name = string.Format( "__{0}__", typeof( T ).FullName );
99 GameObject singletonGo = new GameObject( name );
100 s_Instance = singletonGo.AddComponent<T>();
101 if(s_Instance.gameObject.transform.parent == null){
102 DontDestroyOnLoad( s_Instance );
103 }
104 }
105
106 return s_Instance;
107 }
108 }
109
110 internal static bool IsInstantiated => s_Instance != null;
111
112 protected virtual void Awake()
113 {
114 if(s_Instance == null)
115 {
116 s_Instance = Instance;
117 }
118 }
119 }
120}