Object Pooling

這樣做對,這樣做不對!

原文裏的static加上就成singleton了感覺意義不大,除非只有子彈用這個pool。

 using UnityEngine;
 using System.Collections;
 using System.Collections.Generic;

 public class ObjectPoolScript : MonoBehaviour
 {
     public GameObject pooledObject;
     public int pooledAmount = 20;
     public bool willGrow = true;

     public List<GameObject> pooledObjects;

     void Start ()
     {
         pooledObjects = new List<GameObject>();
         for(int i = 0; i < pooledAmount; i++)
         {
             GameObject obj = (GameObject)Instantiate(pooledObject);
             obj.SetActive(false);
             pooledObjects.Add(obj);
         }
     }

     public GameObject GetPooledObject()
     {
         for(int i = 0; i< pooledObjects.Count; i++)
         {
             if(pooledObjects[i] == null)
             {
                 GameObject obj = (GameObject)Instantiate(pooledObject);
                 obj.SetActive(false);
                 pooledObjects[i] = obj;
                 return pooledObjects[i];
             }
             if(!pooledObjects[i].activeInHierarchy)
             {
                 return pooledObjects[i];
             }    
         }

         if (willGrow)
         {
             GameObject obj = (GameObject)Instantiate(pooledObject);
             pooledObjects.Add(obj);
             return obj;
         }

         return null;
     }

 }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章