Christian Henschel
Software Engineer
Pooling Part 2: How to use the pool (incl. Demo project)
In the first part
of the pooling series I explained why you should use pooling and did a simple implementation of a pool class using a stack. In this post I’m going to show you an example how to use the prior work in your project.
For this we create a scene with an endless amount of flying cubes that are spawned at the right border of the screen and will fly to the opposite side.
Something that looks like this:
Ok, let’s do this
Given you’ve got the code from the previous part of the pooling tutorial, we only need a prefab and an additional script for this one to work.
For the prefab you can go with whatever you want. I went with the red cubes you see above.
The script is called Spawner.cs and implements two methods: Spawn() and Update(). To create a new cube at the right side of the screen the Spawn() method is called every x seconds. The Update() method updates the position and rotation of all flying cubes.
See the code:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
public class Spawner : MonoBehaviour
{
List<GameObject> allObjects;
void Start ()
{
// cache all created cubes for transform manipulations
allObjects = new List<GameObject>();
// Periodically spawn a new object
InvokeRepeating("Spawn", 1, 0.6f);
InvokeRepeating("UpdateUI", 0.1f, 0.2f);
}
/**
* Spawn a new cube at the spawner position adding some randomness to it.
*/
void Spawn()
{
var obj = Pool.Instance.Pop();
if (obj != null)
{
var randomPosition = new Vector3(0, Random.Range(-5, 5), Random.Range(-2, 5));
obj.transform.position = transform.position + randomPosition;
obj.transform.Rotate(Random.Range(0, 360), Random.Range(0, 360), Random.Range(0, 360));
// Store object in a list for movement stuff (see Update());
allObjects.Add(obj);
}
}
void Update()
{
// Move all objects. If an object x-position has reached -20 it is pushed back into the pool.
for(int i = allObjects.Count-1; i >= 0; i--)
{
allObjects[i].transform.Translate(-0.1f, 0, 0, Space.World);
allObjects[i].transform.Rotate(-1, 0, 0);
if (allObjects[i].transform.position.x < -20)
{
Pool.Instance.Push(allObjects[i]);
allObjects.RemoveAt(i);
}
}
}
}
Unity demo project
You can download the whole Unity project here. ![]()