Custom Search

dimanche 8 septembre 2013

Simple Pool of Prefabs for Unity3D Game Engine

Recently I faced a pooling problem in my game. My prefabs were instantiated at run time and it caused some performance issues. Thats why I decided to implement a simple pool of prefabs myself as other pools had a significant overhead in functionality for my project. 

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 cubePrefabs
PrefabPool cubesPool =
new PrefabPool(cubePrefab, parent, initialPoolSize, growth, maxPoolSize);
What 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.
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 pool
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);
As you can see in the hierarchy these three cubes were retrieved from the pool and not instantiated:
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);
cubesPool.RecyclePrefab(retrievedCubeInstance2);
This is what the picture looks like after recycling:
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