28 {
29 get
30 {
32 {
33 Debug.LogWarning($"[Singleton<{typeof(T)}>] Instance will not be returned because the application is quitting.");
34 return null;
35 }
36 lock (Lock)
37 {
38 if (_instance != null)
39 {
40 return _instance;
41 }
42
43 var instances = FindObjectsOfType<T>();
44 var count = instances.Length;
45 if (count == 0)
46 {
47 Debug.Log($"[Singleton<{typeof(T)}>] An instance is needed in the scene and no existing instances were found, so a new instance will be created.");
48 return _instance = new GameObject($"(Singleton){typeof(T)}").AddComponent<T>();
49 }
50 if (count > 1)
51 {
52 Debug.LogWarning($"[Singleton<{typeof(T)}>] There should never be more than one Singleton of type {typeof(T)} in the scene, but {count} were found. The first instance found will be used, and all others will be destroyed.");
53 for (var i = 1; i < instances.Length; i++)
54 {
55 Destroy(instances[i]);
56 }
57 }
58
59 return _instance = instances[0];
60 }
61 }
62 }