How to make my Object Pool persists across different scenes?

I have a simple Object Pool written exactly like this

List<GameObject> ObjectPool;
public GameObject ObjectToBePooled;
public int ObjectsPooledCount;

void Awake()
{
     ObjectPool = new List<GameObject>();
     FillObjectPool();
}

void FillObjectPool()
{
     for(int i = 0; i < ObjectsPooledCount; i++)
     {
          GameObject obj = Instantiate(ObjectToBePooled) as GameObject;
          DontDestroyOnLoad(obj);
          obj.SetActive(false);
          ObjectPool.Add(obj);
     }
}

I think, invoking the DontDestroyOnLoad(PooledObject) (see line 16) make the PooledObject persists across levels but the ObjectPool won’t. If PooledObject persists across different scenes how can I access each of them? Since, ObjectPool was initialized(ObjectPool = new List();) again by Awake method by loading different scene or reloading the current scene.

Set your DontDestroyOnLoad once for the ObjectPool rather than the single objects in the list.
I’m not sure if that will apply to the objects added to the list as well, so you might still need to set the DontDestroy on them as well. But still you will need to make the pool itself not getting destroyed. There’s simply no need to keep the objects but not the pool itself.

Unfortunately there’s no overload method for DontDestroyOnLoad for Collections

You have that script attached to GameObject? Then you could just call in Awake DontDestoroyOnLoad(gameObject) as that would be best way to handle your problem. Another way would be using some sort of XML solution, it is easy serialize / deserialize on fly

Great! My ObjectPool is now preserved across different scenes.
I really forgot that my ObjectPool was attached on a GameObject.

BTW Thanks!

No problemo :smile: