對象池的概念:在激活對象時,它從池中提取。在停用對象時,它放回池中,等待下一個請求。(來自百度);ide
背景:跑酷遊戲,道路上有障礙物,角色身後的障礙物消失,角色前面隨機生成障礙物this
你所須要的最基本的三樣東西:spa
一、一個池子:用來裝你所需的物品,和回收物品;.net
二、一個取物品的方法;orm
三、一個放物品的方法;對象
有這3樣東西,你就能夠建造對象池了blog
如下是完整的代碼部分,裏面有詳細的註釋遊戲
- using UnityEngine;
- using System.Collections;
- using System.Collections.Generic;
-
-
- public class GameObjectPool : MonoBehaviour {
-
-
-
-
- public static GameObjectPool instance;
-
-
- Dictionary<string, List<GameObject>> pool = new Dictionary<string, List<GameObject>>() { };
-
- void Start () {
- instance = this;
- }
-
-
-
- public GameObject GetPool(GameObject go,Vector3 position)
- {
- string key = go.name+"(Clone)";
-
- GameObject rongqi;
-
-
-
- if (pool.ContainsKey(key) && pool[key].Count > 0)
- {
-
- rongqi = pool[key][0];
- pool[key].RemoveAt(0);
- }
- else if (pool.ContainsKey(key) && pool[key].Count <= 0)
- {
-
- rongqi = Instantiate(go,position,Quaternion.identity) as GameObject;
- }
- else
- {
-
- rongqi = Instantiate(go, position, Quaternion.identity) as GameObject;
- pool.Add(key, new List<GameObject>() { });
- }
-
-
- rongqi.SetActive(true);
-
-
- foreach (Transform child in rongqi.transform)
- {
- child.gameObject.SetActive(true);
- }
-
-
- rongqi.transform.position = position;
- return rongqi;
- }
-
-
- public void IntoPool(GameObject go)
- {
-
- string key = go.name;
- pool[key].Add(go);
- go.SetActive(false);
- }
-
- }