Object Pooling

Learn how to create a simple object pooler in Unity3D in our series about building a 3D shooter on rails.

This is a continuation of Final Parsec's tutorial series on building a space-themed rail shooter with Unity3d. In this tutorial, I'll be going over how to create a managed object pool. This will allow you to reduce the number of GameObjects that are instantiated and destroyed, thus improving performance.

In this video tutorial, I'll discuss how I created a simple object pool to manage our projectiles and explosions.

A basic implementation would look like this:


public static List pool = new List();
public static GameObject GetObject(Vector3 worldPosition)
{
    GameObject go = null;

    if (pool.Count != 0)
    {
        go = PrefabAccessor.pool[0];
        pool.RemoveAt(0);
    }

    if (go== null)
    {
        go= (Instantiate(objectPrefab, worldPosition, Quaternion.Euler(Vector3.zero)) as GameObject);
    }
    else
    {
        go.transform.position = worldPosition;
    }
    return go;
}

And the code to return the object to the pool would look like this:


void BackInThePool()
{
    transform.position = new Vector3(transform.position.x, -99, transform.position.z);
    pool.Add(this.gameObject);
}

You can follow along with the development of the project and find the source code from the tutorial on GitHub.

Recommended posts

We have similar articles. Keep reading!

Space Snakes Alpha Look

Video of Space Snakes, Final Parsec's upcoming 2D platformer, in its alpha state.

Tower Defense Tutorials Part 2

The second video tutorial of a series which takes you through the process of building a tower defense game.

Space Snakes Concept Art

Take a sneak peak at Space Snakes, Final Parsec's 2D platformer made with PyGame, with a slideshow of some concept art and some early screenshots.

Parallax for Dummies

An enlightening guide on how to create a simple parallax effect in Unity. Using parallax is a really cool way to breathe life into your games.

Comments

Log in or sign up to leave a comment.