【常用】对象池
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;/// <summary>
/// 對象池
/// </summary>
public class GameObjectPool : MonoSingleton<GameObjectPool>
{ //1.對象池private Dictionary<string, List<GameObject>> cache;//private Dictionary<string, List<GameObject>> obj = new Dictionary<string, List<GameObject>>();//初始化:在對象創建時執行一次protected override void Init(){base.Init();cache = new Dictionary<string, List<GameObject>>();}//2.創建對象/// <summary>/// 通過對象池創建對象/// </summary>/// <param name="key">需要創建的對象種類</param>/// <param name="prefab">需要創建的預制件</param>/// <param name="pos">創建的位置</param>/// <param name="dir">創建的旋轉</param>/// <returns></returns>public GameObject CreateObject(string key, GameObject prefab, Vector3 pos, Quaternion dir){ //在池中查找 GameObject tempGo = FindUsableObject(key);//如果沒有找到if (tempGo == null){//創建物體 tempGo = Instantiate(prefab);//加入池中Add(key, tempGo);//將通過對象池創建的物體,存入對象池子物體列表中。tempGo.transform.SetParent(transform);}//使用UseObject(tempGo, pos, dir);return tempGo;}private void UseObject(GameObject go,Vector3 pos, Quaternion dir){ //先設置位置go.transform.position = pos;go.transform.rotation = dir;//再啟用物體go.SetActive(true); //重置通過對象池創建物體的所有腳本對象foreach (var item in go.GetComponentsInChildren<IResetable>()){item.OnReset();}}private void Add(string key, GameObject tempGo){//如果池中沒有鍵 則 添加鍵if (!cache.ContainsKey(key)) cache.Add(key, new List<GameObject>());//將物體加入池中cache[key].Add(tempGo);}private GameObject FindUsableObject(string key){if (cache.ContainsKey(key)){// public delegate bool Predicate<T>(T obj);//查找池中禁用的物體return cache[key].Find(o => !o.activeInHierarchy);}return null;}//3.即時回收public void CollectObject(GameObject go){go.SetActive(false);}//4.延遲回收public void CollectObject(GameObject go, float delay){StartCoroutine(DelayCollect(go, delay));}private IEnumerator DelayCollect(GameObject go, float delay){yield return new WaitForSeconds(delay);CollectObject(go);}//5.清空public void ClearAll(){ //將字典中所有鍵存入集合List<string> listKey =new List<string>(cache.Keys);foreach (var item in listKey){//遍歷集合元素 刪除字典記錄Clear(item);}}public void Clear(string key){ //倒序刪除for (int i = cache[key].Count -1; i>=0 ; i--){Destroy(cache[key][i]);}//在字典集合中清空當前記錄(集合列表)cache.Remove(key);}
}
?
總結
- 上一篇: 【常用】加载配置文件管理资源路径
- 下一篇: 在unity调用WebService的接