码迷,mamicode.com
首页 > 编程语言 > 详细

Unity单例

时间:2015-07-28 12:51:54      阅读:110      评论:0      收藏:0      [点我收藏+]

标签:

1、非Mono单例:

 1 using System;
 2 using System.Reflection;
 3 using System.Collections.Generic;
 4 
 5 public static class Singleton<T> where T : class
 6 {
 7     static volatile T _instance;
 8     static object _lock = new object();
 9     
10     static Singleton()
11     {
12     }
13 
14     public static T Get()
15     {
16         if (_instance == null)
17         {
18             lock (_lock)
19             {
20                 if (_instance == null)
21                 {
22                     ConstructorInfo constructor = null;
23                     try
24                     {
25                         constructor = typeof(T).GetConstructor(BindingFlags.Instance |
26                                                                BindingFlags.NonPublic, null, new Type[0], null);
27                     }
28                     catch (Exception e)
29                     {
30                         throw e;
31                     }
32 
33                     if (constructor == null || constructor.IsAssembly)
34                     {
35                         throw new Exception(string.Format("A private or protected constructor is missing for ‘{0}‘.", typeof(T).Name));
36                     }
37 
38                     _instance = (T)constructor.Invoke(null);
39                 }
40             }
41         }
42         return _instance;
43     }
44 }

  调用方法:Singleton<XXX>.Get(),XXX表示非继承MonoBehavior的类的类名。

2、Mono单例:

 1 using System;
 2 using System.Collections.Generic;
 3 using UnityEngine;
 4 
 5 public static class MonoSingleton<T> where T : MonoBehaviour 
 6 { 
 7     private static T _instance; 
 8     
 9     public static T Get() 
10     { 
11         if (_instance == null) 
12         { 
13             _instance = UnityEngine.Object.FindObjectOfType<T>(); 
14         } 
15 
16         return _instance; 
17     } 
18 }

  调用方法:MonoSingleton<XXX>.Get(),XXX表示继承MonoBehavior的类的类名。

 

Unity单例

标签:

原文地址:http://www.cnblogs.com/oy-caw/p/4682317.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!