acastrodev
2/19/2015 - 1:20 PM

Object Pooling

Object Pooling

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
 
public class Pool : MonoBehaviour
{
    [SerializeField]
    [Tooltip("Your object can be added to Pool visually by adding it here.")]
    private List<GameObject> pooledObjects;
 
    private GameObject pool;
 
    private void Start()
    {
        pool = new GameObject("_pool");
        pool.SetActive(false);
 
        if (pooledObjects != null)
        {
            foreach (var obj in pooledObjects)
            {
                Add(obj);
            }
        }
 
        // You can also add your resources by code here
        // Example: Add(Resources.Load("MyCoolResource"), 20);
    }
 
    /// <summary>
    /// Method to add game objects to pool.
    /// </summary>
    /// <param name="obj">Name of object that will be pooled.</param>
    /// <param name="count">Times that will be pooled.</param>
    private void Add(Object obj, int count = 1)
    {
        for (int i = 0; i < count; i++)
        {
            if (obj == null) return;
            GameObject tempObject = Instantiate(obj) as GameObject;
            tempObject.gameObject.name = tempObject.gameObject.name.Replace("(Clone)", string.Empty);
            tempObject.transform.parent = pool.transform;
        }
    }
 
    /// <summary>
    /// Method to pick game objects from pool.
    /// </summary>
    /// <param name="name">Name of object that will be picked.</param>
    /// <param name="newOwner">Name of object that will hold the object picked.</param>
    /// <param name="position">Position of object picked.</param>
    /// <returns></returns>
    public GameObject Pick(string name, GameObject newOwner, Vector3 position)
    {
        for (int i = 0; i < pool.transform.childCount; i++)
        {
            GameObject current = pool.transform.GetChild(i).gameObject;
 
            if (current.name == name)
            {
                current.transform.parent = newOwner == null ? null : newOwner.transform;
                current.transform.position = position;
                current.transform.localScale = Vector3.one;
                return current;
            }
        }
        return null;
    }
 
    /// <summary>
    /// Drop game object returning it to pool.
    /// </summary>
    /// <param name="obj">Object to be returned to pool.</param>
    public void Drop(GameObject obj)
    {
        obj.transform.parent = pool.transform;
    }
}