The implementation is ported from Nicolas Gramlich's Andengine pool implementation. The project below also contains an example of how to use this pool.
Simple Pool of Prefabs for Unity3D Game Engine on GitHub.
The usage is extremely simple. First you create an instance of PrefabPool (there are overloaded constructors for flexibility). The constructor with all parameters:
// Create pool of cubes containing instantiated cubePrefabsWhat we have now is a set of instantiated and inactive objects. We do this when our game is loading to avoid further runtime prefab instantiations. We also pass a parent transform to constructor to avoid all these clones being located in Hierarchy root.
PrefabPool cubesPool =
new PrefabPool(cubePrefab, parent, initialPoolSize, growth, maxPoolSize);
Ok, now when out pool of cubes is ready to use we are ready to obtain items from it.
// position, rotation and scale for prefab obtained from the poolAs you can see in the hierarchy these three cubes were retrieved from the pool and not instantiated:
Vector3 pos = new Vector3(2, 2, 2);
Quaternion rotation = Quaternion.Euler(45.0f, 45.0f, 45.0f);
Vector3 scale = new Vector3(2, 2, 2);
Transform retrievedCubeInstance1 = cubesPool.ObtainPrefab(pos, rotation, scale);
Transform retrievedCubeInstance2 = cubesPool.ObtainPrefab(pos * 2, rotation, scale);
Transform retrievedCubeInstance3 = cubesPool.ObtainPrefab(pos * 3, rotation, scale);
If you try to obtain instance from the pool when it is full, the pool will grow by the growth value specified in the constructor. Now the only thing that is left is to recycle instances. Their position and scale will be reset to Vector3.zero , rotation to Quaterniont.identity and they will become inactive. Code to recycle items:
cubesPool.RecyclePrefab(retrievedCubeInstance1);This is what the picture looks like after recycling:
cubesPool.RecyclePrefab(retrievedCubeInstance2);
Summary: This project provides a simple implementation for pool of prefabs to avoid performance issues with run-time prefab instantiation.
Aucun commentaire:
Enregistrer un commentaire