Object Pooling
Creating and destroying objects every time something fires, lands or appears costs time and produces garbage. A pool keeps finished objects aside and hands them out again. The org.mass4.turian.pooling brick provides two kinds of pool in the Turian.Pooling namespace:
ObjectPool<T>reuses plain C# objects of any class.NodePoolreuses instances of a prefab, such as bullets, effects or list rows.
After warm-up, getting and releasing an object from a pool allocates nothing.
Install the brick
Pools are a brick, so add it to the project before using them. In Studio, open the Bricks panel and install org.mass4.turian.pooling, or run this in a terminal:
turian-cli brick add org.mass4.turian.pooling
Then add using Turian.Pooling; to the scripts that use a pool. See Bricks for how bricks are installed and kept up to date.
Object pools
Create a pool with a factory that makes a new object when none is idle, and a maximum size:
using Turian.Pooling;
namespace Usercode;
public class Bullet : IPoolable
{
public Vector3 Velocity;
public float Life;
public void OnGetFromPool() => Life = 2f;
public void OnReleaseToPool() => Velocity = Vector3.Zero;
}
public class Gun : Component
{
readonly ObjectPool<Bullet> bullets = new(static () => new Bullet(), maxSize: 256);
public override void OnAwake() => bullets.Prewarm(64);
public Bullet Fire(Vector3 velocity)
{
var bullet = bullets.Get();
bullet.Velocity = velocity;
return bullet;
}
public void Retire(Bullet bullet) => bullets.Release(bullet);
}
Prewarm(count) creates up to count objects ahead of time, so the first shots do not pay for allocation. Get hands out an idle object, or creates one while the pool may still grow, and throws when the pool is exhausted. TryGet returns false instead of throwing. Release returns an object to the pool; releasing an object that is already idle, or one the pool does not own, throws.
Bullet implements IPoolable, so the pool calls OnGetFromPool before the object reaches Fire's caller and OnReleaseToPool before the object is stored again. That is where it resets its state.
MaxSizeis the most objects the pool owns at once, idle and handed out together.AutoExpand: falsestopsTryGetandGetfrom creating objects beyond those already in the pool.Adoptputs an object you created elsewhere into the pool as an idle one.IdleCount,ActiveCountandOwnedCountreport how many objects are waiting, handed out, and in total.CanGrowtells whether the pool may still create or adopt an object.Cleardiscards every idle object and calls theonDisposecallback on each. Objects that are handed out stay owned until they are released.- The constructor takes optional callbacks:
onGetruns as an object leaves the pool,onReleaseas it returns, andisAlivedecides whether an object can still be used. An object that failsisAliveis dropped instead of reused, which suits objects whose underlying resource can be destroyed.
Objects that implement IPoolable are told when they leave and return to the pool. The IPoolable interface has two methods, OnGetFromPool() and OnReleaseToPool(); the Bullet above is one example. Plain objects without the interface can use the onGet and onRelease callbacks of the constructor instead.
The pool is not thread-safe. Use it from the game loop, which is the thread the engine runs your components on.
Node pools
A NodePool reuses a prefab's node tree. You create it from the scene manager and the prefab reference, usually in OnAwake:
using Turian.Pooling;
namespace Usercode;
public class Shooter : Component
{
public AssetReference<Prefab>? BulletPrefab;
[InjectService, System.Text.Json.Serialization.JsonIgnore]
public ISceneManager? Scenes { get; private set; }
NodePool? bullets;
public override void OnAwake()
{
bullets = NodePool.ForPrefab(Scenes!, BulletPrefab!, maxSize: 128);
}
public override void OnStart() => Async.Run(_ => Prewarm());
async ValueTask Prewarm() => await bullets!.PrewarmAsync(32);
public void Fire(Vector3 position) => Async.Run(_ => FireAsync(position));
async ValueTask FireAsync(Vector3 position)
{
var bullet = await bullets!.GetAsync(parent: Node);
if (bullet is null)
{
return; // every node the pool may own is in use
}
bullet.Position = position;
}
public void Recycle(Node bullet) => bullets!.Release(bullet);
public override void OnDestroy() => bullets?.Dispose();
}
The NodePool rules are these:
PrewarmAsync(count)creates nodes ahead of use, withinMaxSize, so that later calls do not wait for loading.TryGet(out node, parent)hands out an idle node and never creates one, so it never allocates. It returnsfalsewhen no node is idle.GetAsync(parent)does whatTryGetdoes, and creates a node when none is idle and the pool may still grow. It returnsnullwhen every node the pool may own is handed out.- A handed-out node is active under the parent you pass. Pass
nullto leave it without a parent. Release(node)deactivates the node, parks it under the pool'sRoot, and calls theIPoolablecallbacks of its components. Idle nodes sit there, out of every update and query of the scene.- Every component that implements
IPoolable, on the node or on any of its children, is told when the node is handed out and when it is released. Disposedestroys the idle nodes and theRoot. Nodes still handed out are destroyed when they are released afterwards.
NodePool is IDisposable. Dispose it when the owner goes away, as the example does in OnDestroy.
Gotchas
- Release what you get. A handed-out object that is never released is never reused, and counts against
MaxSize. - Reset state when an object comes back. Pools do not clear your fields; use
IPoolable, or theonGetandonReleasecallbacks, to do it. - A pooled node is reused as is. Its components keep their values until
OnReleaseToPoolor your own code resets them. - A pooled node keeps its transform and component values from its last use. Set the position and anything else the next use needs after
GetAsyncorTryGet, or reset it inOnGetFromPool.
Next steps
- Prefabs explains the prefabs a
NodePoolcopies, and how to instantiate one directly. - Components covers the lifecycle callbacks that pooled components use.
- Bricks explains how to add and update the pooling brick.