Page 1 of 1

Unity Scripting : Object Pooling

PostPosted: Wed Feb 11, 2015 6:15 pm
by BenChang
Object pooling is an alternative to instantiation, where you have a fixed size list of objects and only activate them and deactivate them instead of instantiating and destroying on the fly. Can be useful when you have a high rate of spawn and destroy, because those operations do come with a cost, both in allocating memory and initializing objects, and in de-allocating and garbage collecting memory after a destroy. With a lot of create/destroy happening every frame, your framerate can suffer. Object pooling can be useful particularly for things like bullet hell shooters.

In this example, create a prefab with the "TimedDeactivate" script applied to it. Create another GameObject with the Spawner script on it/


Code: Select all
// Spawner.cs
using UnityEngine;
using System.Collections;
using System.Collections.Generic;

// Spawner for object pooling example

public class Spawner : MonoBehaviour {
   private List<GameObject> things;
   public GameObject prefab;
   
   public int poolsize;
   
   // Use this for initialization
   void Start () {
      things = new List<GameObject> ();
      for (int i=0;i<poolsize;i++)
      {
         GameObject g = Instantiate(prefab) as GameObject;
         g.SetActive(false);
         things.Add (g);
      }
   }
   
   // Update is called once per frame
   void Update () {
      if (Input.GetKeyDown(KeyCode.A))
      {
         InvokeRepeating("Spawn",.05f,.05f);
      }
      if (Input.GetKeyUp (KeyCode.A))
      {
         CancelInvoke();
      }
   }
   
   void Spawn()
   {
      GameObject newThing = null;
      newThing = things.Find(delegate (GameObject obj)
         {
            return !obj.activeInHierarchy;
         }
      );
      if (newThing)
      {
         newThing.SetActive(true);
         newThing.SendMessage ("Spawn");   
      }

   }
}