Entity Baking
Entity Baking is the process of pre-processing authoring data into runtime data for use within the ECS system. The BehaviorTree component has a Baker that will automatically bake the behavior tree data if the component is enabled and the behavior tree starts when enabled. Using this baked data does not require any manual steps, but you do need to make sure you spawn the behavior tree Entity and then call BehaviorTree.EnableBakedBehaviorTreeSystem.
Lets consider the example where you want to spawn 100 behavior tree agents using the baked data. The first step is to assign the behavior tree prefab that should be spawned, and then create a system that runs once which calls EnableBakedBehaviorTreeSystem. For the first step we can create a new component that bakes a new prefab:
public struct SpawnData : IComponentData { [Tooltip("The entity prefab that should be spawned.")] public Entity Prefab; } public class EntitySpawner : MonoBehaviour { [Tooltip("A reference to the behavior tree prefab.")] [SerializeField] protected GameObject m_SpawnPrefab; /// <summary> /// Bakes the spawn data. /// </summary> private class Baker : Baker<EntitySpawner> { /// <summary> /// Bakes the data. /// </summary> /// <param name="authoring">The parent authoring component.</param> public override void Bake(EntitySpawner authoring) { if (authoring.m_SpawnPrefab == null) { return; } var entity = GetEntity(TransformUsageFlags.Dynamic); var entityPrefab = GetEntity(authoring.m_SpawnPrefab, TransformUsageFlags.Dynamic); AddComponentObject(entity, new SpawnData { Prefab = entityPrefab, }); } } }
This behavior tree prefab can then be instantiated into a behavior tree entity:
public partial struct EntitySpawnerSystem : ISystem { /// <summary> /// Sets the system requirements. /// </summary> /// <param name="state">The current SystemState.</param> private void OnCreate(ref SystemState state) { state.RequireForUpdate<SpawnData>(); } /// <summary> /// Spawns the entities. /// </summary> /// <param name="state">The current SystemState.</param> private void OnUpdate(ref SystemState state) { state.Enabled = false; var spawner = SystemAPI.ManagedAPI.GetSingleton<SpawnData>(); var entities = state.EntityManager.Instantiate(spawner.Prefab, 100, Allocator.Temp); // Any custom setup for each entity. This can include adding new components, enabling components, setting entity data, etc. // The behavior trees have been baked. Enable the system which starts the behavior trees. BehaviorTree.EnableBakedBehaviorTreeSystem(World.DefaultGameObjectInjectionWorld); } }
After all of the behavior trees have been baked EnableBakedBehaviorTreeSystem is called which will start the entity behavior tree. This method can be called any number of times – for example, if you are spawning new entities then EnableBakedBehaviorTreeSystem should be called again.