41 lines
		
	
	
		
			865 B
		
	
	
	
		
			C#
		
	
	
	
		
		
			
		
	
	
			41 lines
		
	
	
		
			865 B
		
	
	
	
		
			C#
		
	
	
	
|  | using UnityEngine; | |||
|  | using System; | |||
|  | 
 | |||
|  | public class TGSingleton<T> : MonoBehaviour where T : class | |||
|  | { | |||
|  |      | |||
|  |     private static T _instance; | |||
|  |     public static T Instance | |||
|  |     { | |||
|  |         get | |||
|  |         { | |||
|  |             if (_instance == null) | |||
|  |             { | |||
|  |                 var previous = FindObjectOfType(typeof(T)); | |||
|  |                 if (previous) | |||
|  |                 { | |||
|  |                     _instance = previous as T; | |||
|  |                 } | |||
|  |                 else | |||
|  |                 { | |||
|  |                     string name = typeof(T).ToString(); | |||
|  |                     var go = new GameObject("__"+name); | |||
|  |                     _instance = go.AddComponent(typeof(T)) as T; | |||
|  |                     DontDestroyOnLoad(go); | |||
|  |                 } | |||
|  |             } | |||
|  | 
 | |||
|  |             return _instance; | |||
|  |         } | |||
|  |     } | |||
|  | 
 | |||
|  |     private void Awake() | |||
|  |     { | |||
|  |         Initialize(); | |||
|  |     } | |||
|  | 
 | |||
|  |     public virtual void Initialize() | |||
|  |     { | |||
|  | 
 | |||
|  |     } | |||
|  | } |