Unity3d: creating multiples objects without freezing your game

The problem

While we working in the game Land of the Titans  and Cute Block Crush we came across with this problem: how can we create a pool of complex enemies (more than 1k of triangles per enemy) enemies for a single stage and load the stage as soon as we can.

So, when it came to enemies someone always think about using the pooling technique. This is a good solution but when we need a pool of characters with different weapons, armor and hats we need a way to create them without degrading the performance of the game.

The solution

Fortunatelly Unity provides tools to overcome this situation, the Coroutines.

Coroutines are usuefull in Unity when you have to jobs in background and you don’t want to put more code inside the Update function. The idea is to use Coroutines to instantiate the objects gradually at a fixed rate, let’s see it with and example,


using UnityEngine;
using System.Collections;

public class GraduallyInstantiateObjects : MonoBehaviour {

    [Range (0, 100)]
    public int objectCount; // The number of objects to instantiate.
	[Range(0, 1)]
	public float instantiationTime; // The gap bettween instantiations.

	// The prefab object that you want to instantiate.
	public GameObject objectToInstantiate;

	// Use this for initialization
	void Start () {
		StartCoroutine (GraduallyInstantiate ());
	}
	
	// Update is called once per frame
	void Update () {
	
	}


	//This coroutine gradually creates gameobjects of the given prefab.
	IEnumerator GraduallyInstantiate () {
		for (int i = 0; i < objectCount; i++) {
			yield return new WaitForSeconds (instantiationTime);
			Instantiate (objectToInstantiate, new Vector3 (i, 0, 0), Quaternion.identity);
		}
	}
}

As we can see the class GraduallyInstantiateObjects makes use of Coroutines to create objects just afted the Start () method is executed.

As we said before, the idea behind this solution is to prevent a possible freeze in the game while it creates the enemies. If you are making a game that has a lots of characters or items inside and you want to boos your performace this trick will make the difference. Trust us, it’ll save a lot of your precious game development time.

Well, we hope that you’ll find this article usefull and keep and eye for upcoming Unity tricks.

Thanks for reading us 😀