纳金网

标题: 业余练习:单例模版 [打印本页]

作者: 烟雨    时间: 2016-5-30 00:49
标题: 业余练习:单例模版

单例模版:
单例我就不说了,直接贴代码就行:
//非MonoBehaviour 的模版  就是不需要在Hierarchey中创建物体的单例
  1. public class SigletonNotMono<T> where T :class,new()
  2. {
  3. private static T _instance;
  4. public static T Instance
  5. {
  6.   get{
  7.    if(_instance==null)
  8.     _instance = new T();
  9.    return _instance;
  10.   }
  11. }
  12. }
  13. //MonoBehaviour 单例模版,在游戏创建物体
  14. public class SigletonMono<T> : MonoBehaviour where T:MonoBehaviour
  15. {
  16. private static T _instance;
  17. public static T Instance
  18. {
  19.   get{
  20.    if(_instance==null)
  21.    {
  22.     GameObject singleton = new GameObject();
  23.     _instance = singleton.AddComponent<T>();
  24.     singleton.name = "(singleton)"+typeof(T).ToString();
  25.     DontDestroyOnLoad(singleton);
  26.    }
  27.    return _instance;
  28.   }
  29. }
  30. }
复制代码





欢迎光临 纳金网 (http://wwww.narkii.com/club/) Powered by Discuz! X2.5