Search code examples
c#asynchronousdynamicgarbage-collectionpooling

Unity - "Dynamic" Object pooling


I'm making a small game for android and currently use a pooling system e.g. for enemies, projectiles etc.

As for now I'm Async loading in levels as you play the game which means no loading scene when venturing into a new zone.

Pool is created when new game is started or old save is loaded. It works fine but leaves one issue! With no loading scenes while playing, there's no time to populate pool other than at the beginning. As player could potentially play all the way though in one sitting, that means all pooled objects needs to be loaded and instantiated.

I realize "Dynamically" filling a pool kinda miss the whole idea of pooling in the first place, but I'm curious what solutions people have come up with. Instantiating enemies at level 1 that won't see use until level 10 seem wasteful.

Cheers :)


Solution

  • To extend on my comments, I made an example which you could implement into your code. The enable, disable and OnLevelFinishedLoading should go somewhere into your Level/SceneManager class.

    This should stream in the pooled objects whenever you load a new scene.

    void OnEnable()
    {   
        SceneManager.sceneLoaded += OnLevelFinishedLoading;
    }
    
    void OnDisable()
    {  
        SceneManager.sceneLoaded -= OnLevelFinishedLoading;
    }
    
    void OnLevelFinishedLoading(Scene scene, LoadSceneMode mode)
    {
        StartCoroutine(StartPoolingNextLevel(yourObjectPooler));
    }
    
    private IEnumerator StartPoolingNextLevel(YourObjectPoolerClass yourObjectPooler)
    {
        for (int i = 0; i < yourObjectPooler.AmountToPool; i++)
        {
            yourObjectPooler.PoolItem(); // psuedo code
            yield return new WaitForEndOfFrame();
        }
    }