Entity Pooling
How do I implement object pooling for Bolt entities ?
Internally Bolt implements an interface IPrefabPool
. The default Bolt implementation simply dynamically allocates and destroys prefabs when requested (clearly, the default internal Bolt implementation does no pooling internally). If you wish to override this behaviour, you can implement IPrefabPool
on your own custom class and override Bolt’s implementation using BoltNetwork.SetPrefabPool(IPrefabPool pool)
. If you do this, you have complete control over how Bolt prefabs are created and destroyed. You can then simply implement calls to your own custom pooling solution to convert Bolt from using dynamic instantiation to a pooling pattern. You can even replace prefabs with different prefabs if you wish - for example, if you wanted to have a server prefab and a client prefab, this is possible using this mechanism.
This is the simple pool implementation that Bolt uses by default. Notice that it does not actually pool anything (it just dynamically instantiates and destroys the entity).
using UnityEngine;
using Bolt;
public class DefaultPrefabPool : IPrefabPool
{
public GameObject Instantiate(PrefabId prefabId, Vector3 position, Quaternion rotation)
{
GameObject go;
go = GameObject.Instantiate(LoadPrefab(prefabId), position, rotation);
go.GetComponent<BoltEntity>().enabled = true;
return go;
}
public void Destroy(GameObject gameObject)
{
GameObject.Destroy(gameObject);
}
public GameObject LoadPrefab(PrefabId prefabId)
{
return PrefabDatabase.Find(prefabId);
}
}
In order to use your implementation class, you need to register it when Bolt finishes the startup:
public class MyGlobalListener : Bolt.GlobalEventListener
{
public override void BoltStartDone()
{
BoltNetwork.SetPrefabPool(new MyPool());
}
}