object pooling unity code code example
Example: unity object pooling
List<GameObject>list;
public PoolSystem(int size, GameObject prefab){
list = new List<GameObject>();
for(int i = 0 ; i < size; i++){
GameObject obj = (GameObject)Instantiate(prefab);
list.Add(obj);
}
}
public GameObject GetObject(){
if(list.Count > 0){
GameObject obj = list[0];
obj.RemoveAt(0);
return obj;
}
return null;
}
public void DestroyObjectPool(GameObject obj){
list.Add(obj);
obj.SetActive(false);
}
public void ClearPool(){
for(int i = list.Count - 1; i > 0; i--){
GameObject obj = list.RemoveAt(i);
Destroy(obj);
}
list = null;
}