任务四:基础对象池

这是缓存池脚本


1
using System.Collections; 2 using System.Collections.Generic; 3 using UnityEngine; 4 5 //缓存池模块 6 public class PoolMgr : BaseManager<PoolMgr> 7 { 8 9 //1,创建抽屉 10 public Dictionary<string, List<GameObject>> poolDic = new Dictionary<string, List<GameObject>>(); 11 12 13 14 //2,取出物品 15 public GameObject GetObj(string name) 16 { 17 GameObject obj = null; 18 19 //有抽屉,并且抽屉里的东西数量大于0 poolDic[name]==List<GameObject> 20 if (poolDic.ContainsKey(name) && poolDic[name].Count > 0) 21 { 22 obj = poolDic[name][0]; 23 poolDic[name].RemoveAt(0); 24 25 } 26 else 27 { 28 obj = GameObject.Instantiate(Resources.Load<GameObject>(name)); 29 //把对象名字改的和池子名字一样 30 obj.name = name; 31 } 32 //取出东西的时候要激活它,让其显示 33 obj.SetActive(true); 34 return obj; 35 } 36 37 38 //3,放入物品 39 /// <summary> 40 /// 把物体移回对象池中 41 /// </summary> 42 /// <param name="name">要移回的物品名字</param> 43 /// <param name="obj">要移回到的箱子</param> 44 public void PushObj(string name,GameObject obj) 45 { 46 //东西放进来了,要把他失活,让其隐藏 47 obj.SetActive(false); 48 49 if (poolDic.ContainsKey(name)) 50 { 51 poolDic[name].Add(obj); 52 } 53 else //没有抽屉的时候,要创建一个抽屉 54 { 55 poolDic.Add(name,new List<GameObject>() { obj }); 56 } 57 58 } 59 60 61 62 }

 

 

 

2,这是使用的要生成的对象脚本  要把这个脚本挂载在要实例化的对象上

 1 using System.Collections;
 2 using System.Collections.Generic;
 3 using UnityEngine;
 4 
 5 public class DealyPush : MonoBehaviour
 6 {
 7     // Start is called before the first frame update
 8     //当对象激活时,执行的生命周期函数
 9     void OnEnable()
10     {
11         Invoke("Push",1);
12     }
13 
14     private void Push()
15     {
16         PoolMgr.Instance().PushObj(this.gameObject.name,this.gameObject);       
17     }
18 }

 

posted @ 2020-10-08 00:09  青梨  阅读(215)  评论(0编辑  收藏  举报