Tilt Five™ Unity API  1.3.0
 
Loading...
Searching...
No Matches
Singleton.cs
Go to the documentation of this file.
1/*
2 * Copyright (C) 2020-2022 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;
83 break;
84 }
85 }
86
87
88 if( s_Instance == null )
89 {
90 string name = string.Format( "__{0}__", typeof( T ).FullName );
91 GameObject singletonGo = new GameObject( name );
92 s_Instance = singletonGo.AddComponent<T>();
94 }
95
96 return s_Instance;
97 }
98 }
99
100 internal static bool IsInstantiated => s_Instance != null;
101
102 protected virtual void Awake()
103 {
104 if(s_Instance == null)
105 {
107 }
108 }
109 }
110}
static Singleton()
Definition: Singleton.cs:28
static T Instance
Definition: Singleton.cs:37
static readonly T instance
Definition: Singleton.cs:24
Definition: Log.cs:21