How can I make my pooling script shorter?

Greetings! I’ve had this pooling script for quite some time now, and it works perfectly. However, there’s one thing I’m not satisfied with, and that is the fact that everything is repeated. I’m not sure how I can fix this myself, so I wanted to ask here if anyone knew how I can make this shorter.

The whole script

using UnityEngine;
using System.Collections.Generic;

public class Spawner : MonoBehaviour {


    public GameObject[] enemies;
    public float     [] startWait;
    public float     [] spawnTimer;
    public Transform [] spawnPoints;
    public Transform [] turtleSpawnPoints;


    public int pooledAmountShrimp;
    public int pooledAmountPuffer;
    public int pooledAmountTurtle;
    public int pooledAmountSwords;
    public int pooledAmountBigBoy;


    List<GameObject> pooledShrimp;
    List<GameObject> pooledPuffer;
    List<GameObject> pooledTurtle;
    List<GameObject> pooledSword;
    List<GameObject> pooledBigBoy;


    void Start() {
        pooledShrimp = new List<GameObject>();
        for (int i = 0; i < pooledAmountShrimp; i++) {

            GameObject obj_shrimp =
                (GameObject)Instantiate(enemies[0]);

            obj_shrimp.SetActive(false);
            pooledShrimp.Add(obj_shrimp);
        }


        pooledPuffer = new List<GameObject>();
        for (int i = 0; i < pooledAmountPuffer; i++) {

            GameObject obj_pufferfish =
                (GameObject)Instantiate(enemies[1]);

            obj_pufferfish.SetActive(false);
            pooledPuffer.Add(obj_pufferfish);
        }


        pooledTurtle = new List<GameObject>();
        for (int i = 0; i < pooledAmountTurtle; i++) {

            GameObject obj_turtle =
                (GameObject)Instantiate(enemies[2]);

            obj_turtle.SetActive(false);
            pooledTurtle.Add(obj_turtle);
        }


        pooledSword = new List<GameObject>();
        for (int i = 0; i < pooledAmountSwords; i++) {

            GameObject obj_swordfish =
                (GameObject)Instantiate(enemies[3]);

            obj_swordfish.SetActive(false);
            pooledSword.Add(obj_swordfish);
        }


        pooledBigBoy = new List<GameObject>();
        for (int i = 0; i < pooledAmountBigBoy; i++) {

            GameObject obj_bigboy =
                (GameObject)Instantiate(enemies[4]);

            obj_bigboy.SetActive(false);
            pooledBigBoy.Add(obj_bigboy);
        }


        InvokeRepeating("SpawnShrimp",
                        startWait[0], spawnTimer[0]);

        InvokeRepeating("SpawnPuffer",
                        startWait[1], spawnTimer[1]);

        InvokeRepeating("SpawnTurtle",
                        startWait[2], spawnTimer[2]);

        InvokeRepeating("SpawnSwords",
                        startWait[3], spawnTimer[3]);

        InvokeRepeating("SpawnBigBoy",
                        startWait[4], spawnTimer[4]);
    }


    public GameObject GetPooledShrimp() {
        for (int i = 0; i < pooledShrimp.Count; i++) {

            if (!pooledShrimp[i].activeInHierarchy) {
                return pooledShrimp[i];
            }
        }
        return null;
    }

    public GameObject GetPooledPuffer() {
        for (int i = 0; i < pooledPuffer.Count; i++) {

            if (!pooledPuffer[i].activeInHierarchy) {
                return pooledPuffer[i];
            }
        }
        return null;
    }

    public GameObject GetPooledTurtle() {
        for (int i = 0; i < pooledTurtle.Count; i++) {

            if (!pooledTurtle[i].activeInHierarchy) {
                return pooledTurtle[i];
            }
        }
        return null;
    }

    public GameObject GetPooledSwords() {
        for (int i = 0; i < pooledSword.Count; i++) {

            if (!pooledSword[i].activeInHierarchy) {
                return pooledSword[i];
            }
        }
        return null;
    }

    public GameObject GetPooledBigBoy() {
        for (int i = 0; i < pooledBigBoy.Count; i++) {

            if (!pooledBigBoy[i].activeInHierarchy) {
                return pooledBigBoy[i];
            }
        }
        return null;
    }

    void SpawnShrimp() {

        GameObject obj_shrimp = GetPooledShrimp();
        if (obj_shrimp == null) return;

        int spawnPointIndex = Random.Range
            (0, spawnPoints.Length);

        obj_shrimp.transform.position
            = spawnPoints[spawnPointIndex].position;

        obj_shrimp.SetActive(true);
    }

    void SpawnPuffer() {

        GameObject obj_pufferfish = GetPooledPuffer();
        if (obj_pufferfish == null) return;

        int spawnPointIndex = Random.Range
            (0, spawnPoints.Length);

        obj_pufferfish.transform.position
            = spawnPoints[spawnPointIndex].position;

        obj_pufferfish.SetActive(true);
    }

    void SpawnTurtle() {

        GameObject obj_turtle = GetPooledTurtle();
        if (obj_turtle == null) return;

        int spawnPointIndex = Random.Range
            (0, turtleSpawnPoints.Length);

        obj_turtle.transform.position
            = turtleSpawnPoints[spawnPointIndex].position;

        obj_turtle.SetActive(true);
    }

    void SpawnSwords() {

        GameObject obj_swordfish = GetPooledSwords();
        if (obj_swordfish == null) return;

        int spawnPointIndex = Random.Range
            (0, spawnPoints.Length);

        obj_swordfish.transform.position
            = spawnPoints[spawnPointIndex].position;

        obj_swordfish.SetActive(true);
    }

    void SpawnBigBoy() {

        GameObject obj_bigboy = GetPooledBigBoy();
        if (obj_bigboy == null) return;

        int spawnPointIndex = Random.Range
            (0, spawnPoints.Length);

        obj_bigboy.transform.position
            = spawnPoints[spawnPointIndex].position;

        obj_bigboy.SetActive(true);
    }
}

Snippet of only one spawner

using UnityEngine;
using System.Collections.Generic;

public class Spawner : MonoBehaviour {


    public GameObject[] enemies;
    public float     [] startWait;
    public float     [] spawnTimer;
    public Transform [] spawnPoints;
    public Transform [] turtleSpawnPoints;


    public int pooledAmountShrimp;


    List<GameObject> pooledShrimp;


    void Start() {
        pooledShrimp = new List<GameObject>();
        for (int i = 0; i < pooledAmountShrimp; i++) {

            GameObject obj_shrimp =
                (GameObject)Instantiate(enemies[0]);

            obj_shrimp.SetActive(false);
            pooledShrimp.Add(obj_shrimp);
        }

        InvokeRepeating("SpawnShrimp",
                        startWait[0], spawnTimer[0]);
    }

    public GameObject GetPooledShrimp() {
        for (int i = 0; i < pooledShrimp.Count; i++) {

            if (!pooledShrimp[i].activeInHierarchy) {
                return pooledShrimp[i];
            }
        }
        return null;
    }

    void SpawnShrimp() {

        GameObject obj_shrimp = GetPooledShrimp();
        if (obj_shrimp == null) return;

        int spawnPointIndex = Random.Range
            (0, spawnPoints.Length);

        obj_shrimp.transform.position
            = spawnPoints[spawnPointIndex].position;

        obj_shrimp.SetActive(true);
    }
}

The snippet is basically one of five enemies that will be spawned. I figured I could make it easier for people to read, cause I’m not sure if my code is readable by others or not. So the bottom one is basically just 1/5.

Anyone know how I can optimize this? :slight_smile:

You can have each instance of the script dedicated to just one type of pool, as in your second example, and you can attach multiple instances of the script to your pool manager object. If you’d like, you can give each instance its own “poolName” field, and use that to specify which pool object is being retrieved in a static function, like the following:

// a helper function so that we efficiently hold a list of all spawners
public static Spawner[] all {
get {
if (_all == null) _all = FindObjectsOfType<Spawner>();
return _all;
}
}
private static Spawner[] _all;

public static GameObject SpawnPoolObject(string objectName, Vector3 pos) {
foreach (Spawner s in all) {
if (s.poolName == objectName) {
GameObject newPoolObj = s.GetPooledObject();
newPoolObj.transform.position = pos;
return newPoolObj;
}
}
Debug.LogWarning("No spawner with the name "+objectName+" was found.");
return null;
}

(If you want, you could use a reference to the prefab being spawned/pooled as opposed to a string to reference it. The algorithm is unchanged, you just change the data type you compare against.)

Part of why your pool script seems so long is that you are conflating two functions: repeated spawning and object pooling. You may want to break off the repeating SpawnShrimp (etc) functions into a separate script; it can call Spawner.SpawnPoolObject without being a part of the pool script.

1 Like

Imho your code is perfectly readable and easy to understand.

StarManta: I’m taking a look at it now. I have never used “get”, strings, foreach, and… Generally everything there, so it’ll take me a couple minutes to understand what’s happening.

Duugu: I kind of think so too, but… It’s so NOT ‘dry’ (Don’t repeat yourself), and surely there has to be ways of making this short, clean and effective. What I’ve been doing until now is basically polishing the turd. :stuck_out_tongue:

You could skip separating the unit types and use a single pool for all gameobjects adding a “type” property to the gameobjects. Then you could do all of the creating, spawing, etc. stuff within a single method by passing the units type to the method. This would probably cut the length of your code by 4/5.
But if this would lead to cleaner code? I don’t know. :slight_smile:

1 Like

I think I’ll have to read up on this, cause I couldn’t get StarManta’s script to work, nor do I know how to add a type property. I’m playing around with it and seeing if I can get it to work, but so far I haven’t. :slight_smile:

You could add a script to your gameobjects holding a ‘unitType’ variable. Or use tags to specify the unit type.

One instance per pooled object seems the best approach to me.