Prefab pooling and scene loading

There is one important caveat to this system that has not yet been mentioned: the PrefabPoolingSystem class will outlast the scene's lifetime since it is a static class. This means that when a new scene is loaded, the pooling system's dictionaries will attempt to maintain references to any pooled instances from the previous scene, but Unity forcibly destroys these objects regardless of the fact that we are still keeping references to them (unless they were set to DontDestroyOnLoad()), and so the dictionaries will be full of null references. This would cause some serious problems for the next scene.

We should, therefore, create a method in PrefabPoolingSystem that resets the pooling system in preparation for this likely event. The following method should be called before a new scene is loaded so that it is ready for any early calls to Prespawn() in the next scene:

public static void Reset() {
_prefabToPoolMap.Clear ();
_goToPoolMap.Clear ();
}

Note that if we also invoke a garbage collection during scene transitions, there's no need to explicitly destroy the PrefabPool objects these dictionaries were referencing. Since these were the only references to the PrefabPool objects, they will be deallocated during the next garbage collection. If we aren't invoking garbage collection between scenes, then the PrefabPool and PooledPrefabData objects will remain in memory until that time.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.102.112