對象池----unity中應用

對象池應用在unity中能減小資源消耗,節省內存空間具體原理再也不贅述.函數

如下是他的操做步驟:(注意:對象池中應用到了棧或對隊列!)spa

1).先創建一個(怪物)物體   mMonster;code

2).再創建一個對象池  private Stack<GameObject> monsterPoolorm

:先進後出,後進先出,水杯結構   經常使用方法:  .peek()---->獲取棧頂元素對象

                                                                      .pop()------->出棧,彈棧blog

                                                                      .push()------>壓棧,進棧隊列

隊列:先進先出,後進後出,水管結構 經常使用方法: .peek()------------->獲取隊頭元素內存

                                                                      .Dequeue()-------->移除隊頭資源

                                                                      .Enqueue()--------->移除隊頭it

3).再創建一個池子,用來存放激活過的(怪物)物體,做用是用來判斷場景中有多少個激活的物體,再讓最近激活(棧)(或最開始激活(隊列))的對象給失活;

4).在Start/Awake函數中將兩個對象池賦初值(new一下);

5).建立一個返回值爲(怪物)物體的方法,裏面進行判斷對象池中是否存在所需物體,若是對象池爲空,就實例化一個(先不將其加入對象池),不然就直接拿出對象池中所需的物體

6).建立一個方法,當該(怪物)物體失活(SetActive(Fasle)),將其加入到對象池所在物體的旗下( monster.transform.SetParent(transform);),並將其加入到對象池中,以便下次再用!

代碼參上:

 

 1 using System.Collections;
 2 using System.Collections.Generic;
 3 using UnityEngine;
 4 
 5 public class MySimpleFactory : MonoBehaviour {
 6     public GameObject mMonster;
 7     private Stack<GameObject> monsterPool;
 8     private Stack<GameObject> SetActiveMonsterPool;
 9     
10     void Start () 
11     {
12         monsterPool = new Stack<GameObject>();
13         SetActiveMonsterPool = new Stack<GameObject>();     
14     }        
15     void Update ()
16     {
17         if (Input.GetMouseButtonDown(0))
18         {
19             GameObject tempMonster = TakeMonster();
20             tempMonster.transform.position = Vector3.zero;
21             SetActiveMonsterPool.Push(tempMonster);         
22         }
23         if (Input.GetMouseButtonDown(1))
24         {
25             PushThisGameObjectToMonsterPool(SetActiveMonsterPool.Pop());
26         }
27     }
28 
29     private GameObject TakeMonster() 
30     {
31         GameObject Monster = null;
32         if (monsterPool.Count > 0)
33         {
34             Monster = monsterPool.Pop();
35             Monster.SetActive(true);
36         }
37         else 
38         {
39             Monster = Instantiate(mMonster);
40         }
41         return Monster;
42     }
43     private void PushThisGameObjectToMonsterPool(GameObject xt) 
44     {
45         xt.transform.SetParent(gameObject.transform);
46         xt.SetActive(false);
47         monsterPool.Push(xt);
48     }
49 }
相關文章
相關標籤/搜索