单例思维逻辑啥的其实都很明白,使用的频繁也造就了他的重要性:
设计思路:
每次在使用他的时候,如果有了就直接使用,如果没有就内部创建一个出来故:
实例使用:对象池
using lala;//特殊命名空间可以删除
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Common
{
///<summary>
///
///<summary>
public class MonoSingleton<T> : MonoBehaviour where T:MonoSingleton<T>
{
//public static T Instance { get; private set; }
private static T instance;//实例
public static T Instance
{
get
{
if(instance == null)//如果是空就去找
{
//
instance = FindObjectOfType<T>();
if(instance == null)//没找到就自己添加一个物体来承载当前单例
{
//创建物体添加脚本 名字需要约束(会执行awark)
new GameObject("SingletonOf"+typeof(T)).AddComponent<T>();
}
else
{
instance.Init();
}
}
return instance;
}
}
public void Awake()
//在刚开始就调用如果他已经被创建,就赋值set,因为我们是没有public set的(内部自己赋值保证安全)
{
if(instance == null)
{
instance = this as T;
Init();
}
}
public virtual void Init()
{
}
}
}
public class MonoSingleton<T>:MonoBehaviour where T:MonoSingleton<T>//约束他必须注明类型
{
public static T instance;
public static Instance{
get{
if(instance==null){
instance = findObjectByType<T>();
if(instance==null)
new GameObject("MOnosingleton"+type(T).name);
else
instance.init();
}
return instance;
}
}
private void awake()
{
if(instance==null)
instance = this as T;
init();
}
private vistual void init()
{
}
}