This is a simple pool for optimizing object loading.
All objects in the pool are loaded during initialization, and then retrieved from the pool and returned back to the pool without sacrificing performance.
The pool allows you to completely abandon Instantiate and Destroy after initialization.
For Unity version of at least 2019.1.8 (64-bit)
Current version 1.2.1
SimplePool.GiveObj() instead of using Instantiate(Object).
SimplePool.GiveObj(numElement)-> numElement - number of the Element in editor (SimplePool).
GameObject obj = SimplePool.GiveObj(0);
Checking that the pool is not empty, if the pool is empty it will return null: GameObject obj = SimplePool.GiveObj(0);
if (obj != null)
{
// All further manipulations with the object.
}
After all the transformations of the object, activate it: obj.SetActive(true);
The number of elements in the editor (SimplePool): SimplePool.numObjectsList
Return object to the pool, remove from the scene:
SimplePool.Takeobj() instead of using - Destroy(Object).
SimplePool.Takeobj(GameObject)-> GameObject - is an object that to be returned to the pool. SimplePool.Takeobj(obj);
Example script (Getting an object from a pool):
using UnityEngine;
public class Example : MonoBehaviour
{
GameObject obj;
void Start()
{
obj = SimplePool.GiveObj(0); // 0 - number of the Element in editor (SimplePool).
if (obj != null) // Checking that the pool is not empty.
{
obj.transform.SetPositionAndRotation(transform.position, transform.rotation); // Move the object to the desired position, etc.
obj.transform.parent = transform; // Changing the parent. Optionally. You can leave the pool as the parent of the object.
obj.SetActive(true); // After all the transformations of the object, activate it.
}
}
}
Example script (Return object to the pool):
using UnityEngine;
public class Example : MonoBehaviour
{
void Start()
{
SimplePool.Takeobj(obj); // obj - is an object that to be returned to the pool. The object is moved to the pool and becomes inactive.
}
}