Unity Scripting : Object Pooling

Unity Scripting : Object Pooling

Postby BenChang » Wed Feb 11, 2015 6:15 pm

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;
         things.Add (g);
   // Update is called once per frame
   void Update () {
      if (Input.GetKeyDown(KeyCode.A))
      if (Input.GetKeyUp (KeyCode.A))
   void Spawn()
      GameObject newThing = null;
      newThing = things.Find(delegate (GameObject obj)
            return !obj.activeInHierarchy;
      if (newThing)
         newThing.SendMessage ("Spawn");   

User avatar
Posts: 176
Joined: Mon Jan 17, 2011 4:48 pm

Return to Game Development

Who is online

Users browsing this forum: No registered users and 1 guest