单例模式让我们在开发时非常方便,可以全局随意获取。当我们项目中有较多单例脚本时,需要我们一个个写成单例模式,挺费劲。下面是两个单例模式模板,分别是继承MonoBehaviour 和不继承MonoBehaviour 的单例模板。
继承自MonoBehaviour 模板
public class MonoSingletonBase<T> : MonoBehaviour where T : MonoBehaviour
{
private static object _singletonLock = new object();
private static T _instance;
public static T Instance
{
get
{
if (_instance == null)
{
lock (_singletonLock)
{
T[] singletonInstances = FindObjectsOfType(typeof (T)) as T[];
if (singletonInstances.Length == 0) return null;
if (singletonInstances.Length > 1)
{
if (Application.isEditor)
Debug.LogWarning(
"MonoSingleton<T>.Instance: Only 1 singleton instance can exist in the scene. Null will be returned.");
return null;
}
_instance = singletonInstances[0];
}
}
return _instance;
}
}
}
不继承自MonoBehaviour 模板
public abstract class SingletonBase<T> where T : class, new()
{
private static T _instance = new T();
public static T Instance
{
get { return _instance; }
}
}
在使用时,我们直接让我们的脚本继承上面的模板即可。代码如下:
public class ObjectPool : MonoSingletonBase<ObjectPool>
以上就是我在项目开发中使用的单例模板。
如果本博客对你有帮助,记得点关注哦!