Object pooling in a tower defense game

Hello,

I did the Object Pooling - Unity Learn tutorial to improve the performance of my tower defense game.

It worked well but my game is a little different from the course game, there are several objects that shoot(the turrests), and these objects can be created or sold.

And when I sell one of the towers there are several inactive objects in the hierarchy.

This is the turret script (bullets part)

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

public class Turret : MonoBehaviour
{
// Object Pooling
    [SerializeField] private int pooledAmount = 0;
    List<GameObject> bulletsList;

    void Start()
    {                     
        // Object Pooling
        bulletsList = new List<GameObject>();
        for (int i = 0; i < pooledAmount; i++)
        {
            GameObject obj = (GameObject)Instantiate(bulletPrefab);
            obj.SetActive(false);
            bulletsList.Add(obj);
        }
    }

    void Shoot()
    {
            for (int i = 0; i < bulletsList.Count; i++)
            {
                if(!bulletsList[i].activeInHierarchy)
                {
                    bulletsList[i].transform.position = firePoint.transform.position;
                    bulletsList[i].transform.rotation = firePoint.transform.rotation;
                    bulletsList[i].SetActive(true);
                    if (bulletsList[i] != null)
                    {
                        Bullet bullet = bulletsList[i].GetComponent<Bullet>();
                        bullet.Seek(target);
                    }
                    break;
                }
            }       
        }
    }
}

This is the bullet script (object poolinh part)

using System.Collections;
using UnityEngine;

public class Bullet : MonoBehaviour
{
    void HitTarget()
    {
        GameObject effectIns = (GameObject)Instantiate(impactEffect, transform.position, transform.rotation);
        Destroy(effectIns, 1f);
             
        if (explosionRadius > 0)
        {
            Explode();
        }
        else
        {
            Damage(target);
        }

        gameObject.SetActive(false);
    }

}

This is NodeScript (part of the sale of the turrets)

using UnityEngine;
using UnityEngine.EventSystems;

public class Node : MonoBehaviour
{

    public void SellTurret()
    {      
        //GameObject effect = (GameObject)Instantiate(buildManager.sellEffect, GetBuildPosition(), Quaternion.identity);
        //Destroy(effect, 2f);
              
        Destroy(turret);
     
    }

}

This are SS from my unity screen with 5 turrets created. There you can see the number of inactive objects referring to the bullets of each turret, and everything is ok. It works fine if I don’t sell any turrets.

Now if I sell these turrets and create other turrets, the inactive objects of the sold turrets (destroyed) will remain there, the objects of the new turrets are also there. This can cause many objects at the end of the game, reducing game performance.

My question is: Is there a way to remove these inactive objects from these sold turrets that are in the Hierarchy?

Of course… you just Destroy() them.

When you play with object pooling, you basically become the “Inventory Keeper” of all those objects, and you now have to write extra code to do your bidding.

This code has to be meticulously correct from a bookkeeping standpoint or else you get issues like what you see above.

For 99% of games, object pooling is unlikely to make a visible performance difference.

Object pooling can also have a high cost as far as restructuring the lifetime of objects within your game.

It also greatly increases your engineering burden as far as tracking those lifetimes and reasoning about quantities and excesses and everything else associated such that the “inventory keeper” job continues to be done appropriately, even as your game grows and expands going forward.

https://forum.unity.com/threads/object-pooling.1329729/#post-8405055

1 Like

Yeah after doing some object pooling myself, I wouldn’t go that route again unless one of the following statements were true

  1. My game can’t tolerate any GC
  2. I’m creating/destroying these objects at an extremely high rate
  3. I’m seeing a non-trivial performance hit with each instantiation of this prefab
2 Likes

“2) I’m creating/destroying these objects at an extremely high rate”

How much is an extremely high rate?

In my game in a normal situation, close to the last waves there are at least 30 turrets shooting at enemies.

The firing rate of the turrets is variable, there are turrets that fire every 4 seconds (rocket turret) and this is the slowest of the turrets. On the other hand, it has a turret that shoots 5 bullets per second (machine gun).

I think for a mobile game it is a high rate of objects being instantiated and destroyed every second.

But I really don’t know if it is better to continue in the traditional way by instantiating and destroying bullets or in this new way with object pooling.

This part of having to make a meticulously correct code scared me a little.

I wanted to make sure it was worth trying to make this extra code.

1 Like

Just to update, I finished my game and don’t use object pooling.

For the case of my tower defense game I think it was better to use the normal way to instantiate and destroy the objects. Delay and lag were controlled.

The final result can be checked on google play at https://play.google.com/store/apps/details?id=com.KhaosEntertainment.CrazyBallsTD

3 Likes

Yeah, this sounds like the kind of situation you’d want to use pools for. There are problems that occur in Unity as the result of its Garbage Collector outside of simply just getting long hiccups at regular intervals. It’s non-generational and non-compacting so if you are making many frequent allocations you will chew up many times more memory and take longer to perform allocations due to memory fragmentation. That being said ‘overpooling’ is a thing too. If you have too many objects in your pool then that also increases garbage collection times because, again, Unity’s GC isn’t generational so it has to walk through all of those objects even if it doesn’t make sense to. I kinda wish Unity had a way to flag objects as ‘GC ignore-able’ or something to get around this issue.

As far as the ‘meticulously correct’ thing goes - if people are willing to write software in C++ (what I could consider to be a far more dangerous thing than using pooling) then I see no reason why being correct should scare you off from using a technique when warranted. You shouldn’t be afraid of doing work because it requires you to do it correctly. No offense to Kurt. He gives a lot of really great info, and he’s not entirely off-base with his opinion - a lot of simple games really don’t need it. but in cases like what you have it definitely is something you should be using to some degree unless you are using ECS extensively.

1 Like

Nobody has really adressed the core of the question in this post so I would like to suggest a solution:

When creating the bullets in your Turret Start method, make them children of your turret gameobject. This will cause you to destroy all the bullets when a turret is destroyed. This can easily be done on line 17 in your Turret class where the Instantiate for the bullet is.

The Unity documentation for the Instantiate method has several overloads, some of which take in a Transform parent argument: Unity - Scripting API: Object.Instantiate

This is how the Start() method in your Turret class would look like

void Start()
{                   
    // Object Pooling
    bulletsList = new List<GameObject>();
    for (int i = 0; i < pooledAmount; i++)
    {
        // Note the extra transform causing this gameobject to become the parent of the bullet.
        GameObject obj = (GameObject)Instantiate(bulletPrefab, transform);
        obj.SetActive(false);
        bulletsList.Add(obj);
    }
}

Any particular reason you want to create individual pools for each tower? Why not create a generic pool manager and add your projectiles to a global projectile pool that every tower can pull from. That way, you’re not instantiating x amount of bullets per tower in individual pools, and don’t have to worry about what happens to your pooled objects once you sell the tower.

One way to implement this would be by creating a pool manager such as this:

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

public class PoolManager : MonoBehaviour
{
    [System.Serializable]
    public struct Pool
    {
        public string tag;
        public GameObject prefab;
        public Transform poolHolder;
    }
    public static PoolManager Instance;

    public List<Pool> pools;
    public Dictionary<string, Queue<GameObject>> poolDictionary = new Dictionary<string, Queue<GameObject>>();

    private void Awake()
    {
        Instance = this;
    }
    private void Start()
    {
        foreach (Pool pool in pools)
        {
            Queue<GameObject> objectPool = new Queue<GameObject>();

            poolDictionary.Add(pool.tag, objectPool);
        }
    }

    public GameObject GrabFromPool(string tag)
    {
        if (!poolDictionary.ContainsKey(tag)) throw new System.Exception("Invalid tag passed to pool!");
        if (poolDictionary[tag].Count == 0)
        {
            Pool pool = pools.First(i => i.tag == tag);

            GameObject obj = Instantiate(pool.prefab, pool.poolHolder);
            obj.SetActive(false);
            return obj;
        }

        return poolDictionary[tag].Dequeue();
    }

    public void ReturnToPool(string tag, GameObject obj)
    {
        obj.SetActive(false);
        poolDictionary[tag].Enqueue(obj);
        obj.transform.SetParent(pools.First(i => i.tag == tag).poolHolder);
    }
}

You add this to a gameobject in your scene, then you set up a pool from the list, giving it a unique tag, a reference to a gameobject prefab the pool will hold and a reference to a transform you want your inactive pool objects to be placed under.

Then, from your towers, you “GrabFromPool(yourBulletTag)”, move it to the starting location, pass along any info and let it do it’s thing. When it’s done, you “ReturnToPool(“yourBulletTag”, this.gameObject)” and it will be placed back into the pool to be used again.

Your pool will grow dynamically as required, rather than by a chunk of bullets every time a tower is placed, and all bullets are shared and recycled between all your towers (that use that particular projectile). Every single instance of your bullet that you instantiate will be used, rather than having a ton of them sit around gathering dust, and you only instantiate what your game requires. Plus, you don’t have to destroy them when a tower gets sold.

You can use this for other things as well, like damage numbers, healthbars (assuming you use a single canvas for your healthbars, rather than dozens of worldspace ones), effects, anything that you instantiate/destroy on a regular basis.

There are probably better ways to do this, but it works and is easy to use. If you’re prone to typos though, you may want to create an enum for your tags rather than use a plain string :wink: