🗑

Object Pooling

What's that?

Object pooling is a technique used in video game development to efficiently manage in-game objects. The basic concept of object pooling is to prepare a number of objects beforehand and store them in a "pool" or "pool" to be reused when needed. This is especially useful when games require lots of objects to be created and removed continuously, such as bullets in a shooter game.
Without object pooling, the game will continue to create and delete new objects whenever needed. This process can take up a lot of computer resources, especially if the game requires a lot of objects to be created and removed quickly. With object pooling, objects can be quickly retrieved from the pool without the need to create new objects, thereby saving computer resources.
However, object pooling also has drawbacks. Object pooling requires good planning and implementation in order to work properly and efficiently. Because usually it will require additional work to reset the condition of the objects in the pool where this is usually done automatically without using Object Pooling.

Implementation

Change the use of Instantiate(prefab) to pool.Spawn(prefab) and Destroy(gameObject) to pool.Despawn(gameObject) in your project
// Instantiate(bullet);
Gamepangin.Pool.Spawn(bullet);
​
// Destroy(bullet);
Gamepangin.Pool.Despawn(bullet);
If you use the method above, a new GameObject will be created automatically as the prefab pool provider with default settings to make it easier to use. However, if you want more advanced settings for the pool you need, you can create a new GameObject and add a GameObjectPool component. Then you drag and drop the Prefab object that will be pooled into the Prefab slot section. Here you can set several settings such as Preload, Capacity, etc
GameObject Pool Settings
Objects in the pool will not reset to their original state when they are spawned again. For example, if you do object pooling for bullets in your game, and you use the Rigidbody.Velocity API to provide the movement of the bullet, the velocity will not reset when it is despawned. So when you spawn the bullet and add velocity again, the result of the velocity will be multiplied by the last velocity when the bullet was despawned. Then how to overcome it? For each object that you use in Object Pooling, add a method to reset the object's state to OnEnable / OnDisable
public class Bullet : MonoBehaviour {
​
public float bulletSpeed = 10f;
private Rigidbody rigidbody;
private void Awake() {
rigidbody = GetComponent<Rigidbody>();
}
​
private void OnEnable() {
// Reset velocity first when spawned
rigidbody.velocity = 0f;
​
// Move the bullet by changing the velocity
rigidbody.velocity = Vector3.forward * bulletSpeed;
}
}