🎱Object Pooling
v1.0
Last updated
v1.0
Last updated
The Projectile Pool Manager prefab
should be brought into your scene.
This system maintains a ConcurrentDictionary<GameObject, Queue<GameObject>>
which holds all of the pooled Projectiles, as well as a ConcurrentDictionary<string, Queue<GameObject>>
which holds other GameObjects returned to the pool.
Behaviors will automatically attempt to use the pool unless the Projectile has this feature toggled off.
DestroyBehavior.cs
Any Behavior
created that is intended to destroy the Projectile
should inherit from DestroyBehavior
. This has a built in method that will either put the object back into the pool, or destroy it, depending on the Projectile settings, called automatically when the DoDestroy
event fires.
In the example below, the AreaDamageOnDestroy
behavior overrides DoDestroy()
, and causes some area at the position of the projectile, before calling base.DoDestroy(projectile)
, which will trigger the default behavior -- putting the Projectile back into the pool.
ProjectilePowerDestroy.cs
The Projectile Power Destroy component can be added to objects that are spawned by Projectiles, such as impact particles. Many of the demo Projectiles make use of this pattern. The projectile will spawn an impact particle prefab
whenever it collides. This means we probably want to use the Object Pool on those objects as well, since they'll be used repeatedly.
There are two methods to put Projectiles or GameObjects back into the pool. Both methods have an optional float delay
which will delay the operation that actually puts the object back into the pool.
If you plan on making use of the Object Pool for GameObjects
that are not Projectiles
, then you can use the PutBackGameObject()
method, which will work with any object you'd like to use.
The key for the GameObject
pool is the name of the GameObject
. The " (Clone)" that Unity automatically adds to object names will be removed from the name. This means that you should ensure your objects which you'll be putting into the pool, and taking back out, have unique names from other objects.
The Spawn Behavior will automatically attempt to pull objects from the pool before instantiating new instances, in the SpawnProjectile()
method.
There are two methods to get Projectiles or GameObjects
from the pool. The GetProjectile()
method will first search for the Projectile based on the objectToGet
provided. If it is not found, it will fallback to the GetGameObject()
option.
If you plan on making use of the Object Pool for GameObjects
that are not Projectiles
, then you can use the GetGameObject()
method, which will work with any object you'd like to use.
The Object Pool has a built-in debug logger which you can turn on to see more details about objects going into and out of the pool. The frame number is included as well, which may help illustrate the order of things.