Alpha Accesswebsite_badges_steamwishlistwebsite_badges_steamwishlist

Object pooling for performance in Unity


objectPoolExample64

Object pooling is a technique that you’re bound to need at some point in your game dev career. In fact, you may even be using some form of it (or your game engine might) without realizing it. In a nutshell, it is equivalent to caching. Rather than instantiating objects at runtime as you need them, you should instantiate everything you will need (or estimate you will need) beforehand, and pull from this “pool” when you need them. Instead of destroying objects when they are “dead,” you simply disable them and put them back into the pool.

The classic example in games are bullets: rather than instantiating a new bullet every time characters fire their weapons, and then destroying them when off screen or hitting another character, you simply disable them and move them off screen, then enable and move them back on screen as needed. Obviously, it doesn’t just apply to bullets, so keep an eye out for anything in your game that is instantiated frequently. The most common cases are projectiles and effects, such as explosions, dust, debris, etc, however you could even go as far as using it for common shared UI components for the ultimate in snappy performance.

The benefits to object pooling are: fewer game hiccups and lag due to expensive instantiation and destruction, and better estimation of memory needs up front since pooled objects are always loaded. If you have a lot of objects, you will definitely notice and feel these improvements right away. The only downside is from the developer’s perspective: it requires more attention to initialization of variables in objects as they are enabled and disabled, rather than created and destroyed. In Unity, this means you should handle this logic in OnEnable() and OnDisable() in game objects. Similarly, rather than creating and destroying, you are enabling and disabling the pooled objects.

There are many object pooling scripts in the Asset Store, but it’s easy enough to create your own if you understand the concept. As with all in-house solutions, you can tailor it slightly to better fit your exact needs when crafting your own. I’m including the full script here in case you’d like to use it in your own projects (or improve upon it). Some notes about my implementation:

  • The ObjectPool.cs script is attached to an empty game object in the scene.
  • It’s developed as a singleton, so it has a static reference: ObjectPool.shared
  • It’s designed to store any number of pooled object types, with each containing a game object, the amount to start in the pool, and whether or not the amount can dynamically grow or not. You set these up simply on the game object (see the screenshot example below).
  • To facilitate storing anything, the main data structure is a Dictionary full of Lists, with the keys of the dictionary being the names of the prefabs / game objects to be stored.
  • GetPooledObject() returns a regular instantiated prefab if there is no associated pool, so it’s safe to call from scripts that don’t know if there’s a pool or not.

objectPool

Note: This hasn’t really been stress tested too much, but so far it seems to be working great. I’m not sure if making it too flexible (a Dictionary of Lists) is actually more expensive than instantiating and destroying, thus defeating the purpose, but I imagine it isn’t and I’ll run some tests later.

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

[System.Serializable]
public class PooledObject
{
	public Object objectToPool;
	public int pooledAmount = 20;
	public bool canGrow = true;
}

public class ObjectPool : MonoBehaviour
{
	public static ObjectPool shared;
	public PooledObject[] pooledObjectTypes;

	private Dictionary<string, List<GameObject>> pool;

	void Awake()
	{
		// set up singleton reference
		if (shared == null)
		{
			shared = this;
		}
	}

	void Start()
	{
		// set up the pool and instantiate all initial objects
		pool = new Dictionary<string, List<GameObject>>();
		for (int i = 0; i < pooledObjectTypes.Length; i++)
		{
			PooledObject pooledObjectType = pooledObjectTypes[i];
			pool.Add(pooledObjectType.objectToPool.name, new List<GameObject>());
			for (int i2 = 0; i2 < pooledObjectType.pooledAmount; i2++)
			{
				AddPooledObject(pooledObjectType.objectToPool);
			}
		}
	}

	GameObject AddPooledObject(Object newObject)
	{
		GameObject pooledObject = Instantiate(newObject) as GameObject;
		if (shared.gameObject.transform != null)
		{
			pooledObject.transform.parent = shared.gameObject.transform;
		}
		pooledObject.SetActive(false);
		pool[newObject.name].Add(pooledObject);
		return pooledObject;
	}

	public void DisableAllPooledObjects()
	{
		foreach(string key in pool.Keys)
		{
		    foreach(GameObject pooledObject in pool[key])
		    {
		    	pooledObject.SetActive(false);
		    }
		}
	}

	public List<GameObject> GetPooledObjects(Object gameObject)
	{
		if (!pool.ContainsKey(gameObject.name))
		{
			return null;
		}
		return pool[gameObject.name];
	}

	public GameObject GetPooledObject(Object gameObject)
	{
		// return a regular non-pooled version if there is no pool for this type
		List<GameObject> pooledObjects = GetPooledObjects(gameObject);
		if (pooledObjects == null)
		{
			Debug.Log("Returning non-pooled instance of: " + gameObject.name);
			return (Instantiate(gameObject) as GameObject);
		}

		// return first available inactive pooled object
		for (int i = 0; i < pooledObjects.Count; i++)
		{
			if (!pooledObjects[i].activeInHierarchy)
			{
				return pooledObjects[i];
			}
		}

		// grow the pool if needed and return the new object
		for (int i = 0; i < pooledObjectTypes.Length; i++)
		{
			if (pooledObjectTypes[i].objectToPool.name == gameObject.name)
			{
				if (pooledObjectTypes[i].canGrow)
				{
					return AddPooledObject(gameObject);
				}
				else
				{
					return pooledObjects[0];
				}
			}
		}
		
		// return null if none was created
		// this should be handled by the caller script
		return null;
	}
}

Multiple character sprites using one animation controller


Update 2015.02.26
So, this post is actually a terrible way to go about this. When I was going down this path, I wasn’t aware of the built-in ways to handle something like this. Namely, you just need to create a single character’s animator controller and animation clips to feed it. Then you can create an “Animator Override Controller” that derives from that base animator for each additional character, and simply replace all the clips with unique ones. Part of this blog is to document the journey through my first Unity project, and, well, this is one of those learning experiences.

If you have several characters that your players can choose from, but all share a similar tree of Mecanim states and animations, you can use a single animation controller for all of them. Note that part of the process requires creating layers to “sync” to the master layer, and this is a Unity Pro-only feature. Here’s a quick example of some common player states, and how the process works:

animationStatesWith your animation states set up, make sure that you have created animation clips for each character for each of the states. For example, for the “player_fire” state, you would have animation clips such as “character1_fire”, “character2_fire”, “character3_fire”, etc. Have your first animation clip assigned to the state above.

With the first character all set up, simply add more layers in the animation controller for each character that you have. In the other layers, make sure you have “Sync” enabled (Pro-only feature). This syncs all the states with the top master layer, so all layers share the same states. Then you can simply click a layer to edit, and for each of the states, assign a different animation clip. In this example, I’ve added 4 other characters:

animationLayers

The last step is in your code. You can loop through all the layers in your animator, and set all their layer weights to 0 except for the chosen character, which should be 1. Here’s an example function that does this:

void SetCharacterLayer(int characterLayer)
{
	Animator animator = GetComponent();
	for (int i = 0; i < animator.layerCount; i++)
	{
		float layerWeight = (characterLayer == i) ? 1f : 0f;
		animator.SetLayerWeight(characterLayer, layerWeight);
	}
}

Custom Build Tools


While it’s easy enough to use Unity’s built-in build tools, you can make more customized build commands that are specifically tailored towards your game. This allows you to perform some tasks prior to exporting the final build, such as dynamically generating data files, or dynamically building a list of scenes to include.

buildTools

I have a custom class extending EditorWindow, and on that window I have some simple buttons that perform build-related tasks for me. Here are some simple examples, and I’m sure you can think of more that apply to your own game to save you some time:

Generate a dynamic, custom data file used by the game:
In my example, I will have many “maps” which are Unity scenes loaded into a main scene by LoadLevelAdditive(). I have a build tool that opens every single map, gets information about it, and saves all this data (width, height, supported game modes, etc) to a master maps.json file. That way, my game menus and logic can pull this info from the file at runtime.

Define build scenes in a Constants file, and add them to the build when generating:
This is useful if you have tons of scenes that will be loaded additively (such as my maps from above), and you don’t want to add them all to the build settings dialog manually. If you have a lot of churn during development, with maps being deleted and created continuously, this is a big time saver. I have my main build scenes defined in a Constants.cs file, and I combine this list with all my maps not in the list at build time. Here’s a quick example that doesn’t work on its own as a lot of surrounding code is missing, but gives the general idea:

//---[ Constants.cs ]--------------------------------------

// scenes to include in build (in Constants.cs)
#if UNITY_EDITOR
public static string[] BuildScenes = {
	"Assets/Scenes/TitleScene.unity",
	"Assets/Scenes/OptionsScene.unity",
	"Assets/Scenes/PlayerSetupScene.unity",
	"Assets/Scenes/BattleScene.unity"
};
#endif

//---[ build tools ]---------------------------------------

// combine all the scenes to include:
List allBuildScenes = new List();
allBuildScenes.AddRange(Constants.BuildScenes);
allBuildScenes.AddRange(otherScenesToInclude);

// finally, generate the build:
BuildPipeline.BuildPlayer(
    allBuildScenes.ToArray(),
    buildExportPath,
    buildPlatformTarget,
    BuildOptions.None
);

Pull in information and data from external sources:
I have a data file hosted on a web server that makes it easy for myself and others to continuously contribute to it whenever we have ideas. I can pull down this file in my build process and sync it with the game’s version. That way, we can contribute to it at any time, and it will be included in the next build:

// import external data file
WWW dataFileWWW = new WWW(dataURL);
while (!dataFileWWW.isDone)
{
    EditorUtility.DisplayProgressBar("Importing data...", dataURL, dataFileWWW.progress);
}
File.WriteAllText(Application.dataPath + "/Resources/data.txt", dataFileWWW.text);
AssetDatabase.Refresh();
EditorUtility.ClearProgressBar();

Simple and flexible scrolling behavior


One of the staples of 2D games pioneered in the old school days is seamless scrolling. More specifically, having an endless scrolling behavior that seems infinite. This is usually applied to background layers, and when you combine different layers with varying speeds, you can achieve a very nice parallax effect that sells depth on a flat screen. I’ll be honest – I’m a sucker for anything with sensible parallax. To me, the effect never gets old and instantly makes smaller worlds feel expansive.

The technique is very, very simple. Perhaps it’s one of the first effects that many beginner game programmers are introduced to. It’s also probably one of the most satisfying results you’ll get in a very short amount of time.

In essence, if you create 2 copies of your scrolling layer and place them side by side, you can have them both scrolling in the intended direction, and when one of them is completely off screen, simply move it to the opposite edge. You can see the illusion illustrated here. If you pay attention to the center camera and the two hills, you can see that they appear to be seamless.

parallaxExample

In Unity, it’s simple enough to create a small behavior script that gives the game object a speed to be scrolling at, and to snap back to the other side when off screen. If you apply this script to two identical side-by-side game objects, you can get this seamless behavior. The nice thing about the approach in Unity is that you just need to translate the objects in your Update() method, but you don’t need the offscreen-check performed every update. You can use the MonoBehaviour callback OnBecameInvisible() to handle this:

using UnityEngine;
using System.Collections;

public class Scrolling : MonoBehaviour
{
	public float xSpeed;
	public float ySpeed;

	void Update()
	{
		transform.Translate(new Vector3(xSpeed, ySpeed, 0f));
	}

	void OnBecameInvisible()
	{
		Vector3 newPosition = transform.localPosition;
		Vector3 viewportPoint = Camera.main.WorldToViewportPoint(transform.position);
		
		// move to opposite edge of screen (horizontally)
		if (xSpeed != 0 && (viewportPoint.x < 0f || viewportPoint.x > 1f))
		{
			newPosition.x = -transform.localPosition.x;
		}

		// move to opposite edge of screen (vertically)
		if (ySpeed != 0 && (viewportPoint.y < 0f || viewportPoint.y > 1f))
		{
			newPosition.y = -transform.localPosition.y;
		}

		// move to the new position
		transform.localPosition = newPosition;
	}
}

Give life to explosions and debris


Update 2014.08.22
I did figure out a much better approach. Read the update here!

Update: 2014.07.22
So… my hunch “this is probably too expensive in the end” turned out to be true. I’ve optimized it a little, but this is too expensive to apply to large numbers of game objects (but perfectly fine for just a few). I’ll figure out a more efficient approach for the same effect since I’ll require a lot of debris, and include the new method in a future post.

bouncingDebris2.96

I love debris. Physical particle debris is one of the things that, in my opinion, brings modern low-res games to life. It’s also a technique that simply wasn’t feasible in the 8- and 16-bit eras due to hardware limitations. This is another reason why I would wholeheartedly argue that low-res is not simply “retro,” but a legitimate, timeless aesthetic style all its own. It is familiar yet evolving. I digress!

There are two limitations in Unity 4.3+ that I’ve had to work around to get the effect that I wanted.

The first is that the built in shuriken particle system does not support 2D physics. This means that I must use individual game objects for my debris if I want them to physically interact with the rest of my 2D colliders. So far, this hasn’t been a performance issue as I am keeping my debris in a shared object pool – a topic for a future post.

The second issue is that Unity won’t let you specify gravity in the z-direction; it’s strictly limited to x and y for 2D. My project is top-down, so to get gravity effects along the z-axis, I’m forced to use old school visual tricks to sell it. One such technique is growing sprites as they are closer to you and shrinking as they move away, and also moving them along parabolic arcs in the y direction (while adding this to their “real” y-position).

Going back to my introduction, debris should feel “alive” and dynamic, and in my case I wanted each particle to collide with the environment, and to slightly bounce until they came to rest. You can see in this example that the bounce is quite subtle, but it serves to “ground” everything and when you see it without the bounce, you’ll realize just how much it adds. I’ve always loved this sort of attention to detail in my favorite games, and they really add polish and “glue” to otherwise static objects.

For the bouncing itself, I’m running some simple tweens (using the excellent GoKit tweening library) in the y direction on each particle. The rest of their motion path all comes from a physical force I apply when they are spawned. I created a simple vertical bounce behavior script that I can attach to game objects to simulate this effect, and you can see a version of the script here. This script actually has some issues and will most likely change dramatically before the game is done, but the general idea will be the same. In fact, this is probably too expensive in the end, but so far my performance is still good:

using UnityEngine;
using System.Collections;

public class VerticalBounce : MonoBehaviour
{
    public float minAmplitude = 0.25f;
    public float maxAmplitude = 0.5f;
    public float minBounceTime = 0.25f;
    public float maxBounceTime = 0.5f;
    public int numberOfBounces = 2;
    public float bounceChance = 0.33f;
    
    private float amplitude;
    private float bounceTime;
    private Vector3 currentPosition;

    private float _offset;
    [HideInInspector]
    public float offset
    {
        get { return _offset; }
        set { _offset = value; }
    }

    void OnEnable()
    {
        // sometimes, don't bounce at all
        if (Random.value > bounceChance)
        {
            return;
        }

        // choose a random amplitude and time between the specified range
        amplitude = Random.Range(minAmplitude, maxAmplitude);
        bounceTime = Random.Range(minBounceTime, maxBounceTime);
        
        // create a tween chain that raises and lowers the offset x numberOfBounces times
        GoTweenChain bounceChain = new GoTweenChain();
        for (int i = 1; i <= numberOfBounces; i++)
        {
            _offset = 0f;
            GoTween riseTween = new GoTween(this, bounceTime, new GoTweenConfig()
                .floatProp("offset", amplitude, false)
                .setEaseType(GoEaseType.SineOut)
            );
            GoTween fallTween = new GoTween(this, bounceTime, new GoTweenConfig()
                .floatProp("offset", -amplitude, false)
                .setEaseType(GoEaseType.SineIn)
            );
            bounceChain.append(riseTween).append(fallTween);

            // each bounce should have a lower amplitude and take less time
            amplitude /= 2;
            bounceTime /= 2;
        }
        bounceChain.setOnCompleteHandler((x) => {
            _offset = 0f;
        });
        bounceChain.play();
    }

    void FixedUpdate()
    {
        // add the fake vertical bounce on top of the current y position (additive)
        currentPosition = gameObject.transform.localPosition;
        gameObject.transform.localPosition = new Vector3(currentPosition.x, (currentPosition.y + _offset), currentPosition.z);
    }
}
©2018 Sombr Studio LLC