单例模式基类模块
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//C#中 泛型知识点
//设计模式 单例模式的知识点
//继承这种自动创建的 单例模式基类 不需要我们手动去拖 或者 api去加了
//想用他 直接 GetInstance就行了
public class SingletonAutoMono<T> : MonoBehaviour where T : MonoBehaviour
{
private static T instance;
public static T GetInstance()
{
if (instance == null)
{
GameObject obj = new GameObject();
//设置对象的名字为脚本名
obj.name = typeof(T).ToString();
//让这个单例模式对象 过场景 不移除
//因为 单例模式对象 往往 是存在整个程序生命周期中的
DontDestroyOnLoad(obj);
instance =obj.AddComponent<T>();
}
return instance;
}
protected virtual void Awake()
{
instance = this as T;
}
}
缓存池模块
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PoolMgr :BaseManager<PoolMgr>
{
//缓存池容器(衣柜)
public Dictionary<string,List<GameObject>>poolDic=new Dictionary<string,List<GameObject>>();
/// <summary>
/// 往外拿东西
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public GameObject GetObj(string name)
{
GameObject obj = null;
//有抽屉 并且抽屉里有东西
if (poolDic.ContainsKey(name) && poolDic[name].Count > 0)
{
obj=poolDic[name][0];
poolDic[name].RemoveAt(0);
}
else
{
obj = GameObject.Instantiate(Resources.Load<GameObject>(name));
//把对象名字改的和池子名字一样
obj.name = name;
}
//激活 让其显示
obj.SetActive(true);
return obj;
}
/// <summary>
/// 换暂时不用的东西给我
/// </summary>
public void PushObj(string name, GameObject obj)
{
//失活 让其隐藏
obj.SetActive(false);
//里面有抽屉
if (poolDic.ContainsKey(name))
{
poolDic[name].Add(obj);
}
//里面没有抽屉
else
{
poolDic.Add(name, new List<GameObject>() { obj });
}
}
}