using UnityEngine;
using System.Collections.Generic;
public class chimanage : MonoBehaviour {
public GameObject[] prePrefabs; //各种对象池--
//私有的静态实例
public static chimanage abc;
////懒汉式 单例模式 如果忘记建空物体和拉脚本,可以用懒汉模式
////共有的唯一的,全局访问点
//public static PoolManager Instance
//{
// get
// {
// if (_instance == null)
// {
// GameObject go = new GameObject("PoolManager");
// _instance = go.AddComponent<PoolManager>();
// }
// return _instance;
// }
//}
private void Awake() //饿汉模式,需要建立空物体,将脚本托拽入空物体中
{
abc = this;
IntPool(); //提前创建对象池--
}
void IntPool() //提前创建对象池,在玩家子弹,敌人子弹,敌人不用创建新对象池,外部拖拽预制体就可以--
{
foreach (var prefab in prePrefabs)
{
CreatPool(prefab.name,prefab);
}
}
private Dictionary<string, chi> dic = new Dictionary<string, chi>();
/// 创建对象池
/// </summary>
/// <param name="poolName">对象池名字</param>
/// <param name="prefab">对象池对应的预制体</param>
public void CreatPool(string poolName, GameObject prefab)
{
if (!dic.ContainsKey(poolName))
{
dic[poolName] = new chi(prefab);
}
}
/// 获取对象池对象
/// </summary>
/// <param name="poolName">对象池名字</param>
/// <returns></returns>
public GameObject Get(string poolName)
{
chi pool; //poll是声明,与chi里面参数无联系
if (dic.TryGetValue(poolName, out pool))
{
return pool.Get();
}
else
{
Debug.LogError("对象池:" + poolName + " 不存在!!!");
return null;
}
}
/// <summary>
/// 回收对象
/// </summary>
/// <param name="poolName">对象池的名字</param>
/// <param name="go">对象</param>
public void Save(string poolName, GameObject go)
{
chi pool; //poll是声明,与chi里面参数无联系
if (dic.TryGetValue(poolName, out pool))
{
pool.Save(go);
}
else
{
Debug.LogError("对象池:" + poolName + " 不存在!!!");
}
}
}
网友评论