Created
October 1, 2023 16:46
-
-
Save hungtrinhh/f69702e15d6e3252d8b4080b9c4a18d1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
public class Singleton<T> : MonoBehaviour where T : Component | |
{ | |
private static T instance; | |
private static bool isGameEnd; | |
public static T Instance | |
{ | |
get | |
{ | |
if (instance == null) | |
{ | |
var objs = FindObjectsOfType<T>(); | |
if (objs.Length > 0) | |
{ | |
instance = objs[0]; | |
} | |
if (objs.Length > 1) | |
{ | |
Debug.LogWarning($"have {objs.Length} {typeof(T)} in the scene"); | |
} | |
if (instance == null && !isGameEnd) | |
{ | |
var gobject = new GameObject(typeof(T).ToString()); | |
instance = gobject.AddComponent<T>(); | |
} | |
} | |
return instance; | |
} | |
} | |
private void OnApplicationQuit() | |
{ | |
instance = null; | |
isGameEnd = true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment