kingBook

导航

泛型单例

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public abstract class BaseApp<T>:MonoBehaviour where T:class,new(){
	
	protected static T _instance;

	public static T getInstance(){
		return _instance;
	}

	private void Awake(){
		if(_instance==null){
			_instance=this as T;
			DontDestroyOnLoad(gameObject);
		}else{
			Destroy(gameObject);
		}
	}
	
	private void OnDestroy(){
		if(_instance!=null){
			if(_instance.Equals(this)){
				_instance=null;
			}
		}
	}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class App:BaseApp<App>{

	public void sayHello(){
		Debug.Log("Hello");
	}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Test:MonoBehaviour {

	private void Start(){
		App.getInstance().sayHello();//output: Hello
	}
}

posted on 2019-05-27 12:15  kingBook  阅读(293)  评论(0编辑  收藏  举报