对象池管理器

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 + " 不存在!!!");
    }
}

}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容