반응형
Notice
Recent Posts
Recent Comments
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

Do Something IT

[Unity] ObjectPool 본문

Unity3D

[Unity] ObjectPool

아낙시만더 2015. 4. 13. 01:49
반응형
·미리보기 | 소스복사·
  1. using System.Collections;  
  2.   
  3. using System.Collections.Generic;  
  4.   
  5.    
  6.   
  7. /* 
  8.  
  9.  * Usage 
  10.  
  11.  *  
  12.  
  13.  * CGameObjectPool<GameObject> monster_pool; 
  14.  
  15.  * ... 
  16.  
  17.  *  
  18.  
  19.  * // Create monsters. 
  20.  
  21.  * this.monster_pool = new CGameObjectPool<GameObject>(5, () =>  
  22.  
  23.     {  
  24.  
  25.         GameObject obj = new GameObject("monster"); 
  26.  
  27.         return obj; 
  28.  
  29.     }); 
  30.  
  31.      
  32.  
  33.      
  34.  
  35.     ... 
  36.  
  37.      
  38.  
  39.     // Get from pool 
  40.  
  41.     GameObject obj = this.monster_pool.pop(); 
  42.  
  43.      
  44.  
  45.     ... 
  46.  
  47.      
  48.  
  49.     // Return to pool 
  50.  
  51.     this.monster_pool.push(obj); 
  52.  
  53.  * */  
  54.   
  55. public class CGameObjectPool<T> where T : class  
  56.   
  57. {  
  58.   
  59.     // Instance count to create.  
  60.   
  61.     short count;  
  62.   
  63.       
  64.   
  65.     public delegate T Func();  
  66.   
  67.     Func create_fn;  
  68.   
  69.       
  70.   
  71.     // Instances.  
  72.   
  73.     Stack<T> objects;  
  74.   
  75.    
  76.   
  77.     // Construct  
  78.   
  79.     public CGameObjectPool(short count, Func fn)  
  80.   
  81.     {  
  82.   
  83.         this.count = count;  
  84.   
  85.         this.create_fn = fn;  
  86.   
  87.    
  88.   
  89.         this.objects = new Stack<T>(this.count);  
  90.   
  91.         allocate();  
  92.   
  93.     }  
  94.   
  95.       
  96.   
  97.     void allocate()  
  98.   
  99.     {  
  100.   
  101.         for (int i=0; i<this.count; ++i)  
  102.   
  103.         {  
  104.   
  105.             this.objects.Push(this.create_fn());  
  106.   
  107.         }  
  108.   
  109.     }  
  110.   
  111.       
  112.   
  113.     public T pop()  
  114.   
  115.     {  
  116.   
  117.         if (this.objects.Count <= 0)  
  118.   
  119.         {  
  120.   
  121.             allocate();  
  122.   
  123.         }  
  124.   
  125.    
  126.   
  127.         return this.objects.Pop();  
  128.   
  129.     }  
  130.   
  131.       
  132.   
  133.     public void push(T obj)  
  134.   
  135.     {  
  136.   
  137.         this.objects.Push(obj);  
  138.   
  139.     }  
  140.   
  141. }  


반응형

'Unity3D' 카테고리의 다른 글

Simple Observer Pattern  (0) 2015.05.11
포물선정보  (0) 2015.04.28
[Unity]범위내 적에게 데미지 주기  (0) 2015.04.13
레퍼런스 함수에 LayerMask 할당하기  (0) 2015.04.13
[Unity Ngui] Ngui 텍스쳐 마스킹 하기~  (0) 2015.03.25
Comments