Entity Baking

Entity Baking is the process of pre-processing authoring data into runtime data for use within the ECS system. The StateMachine component has a Baker that will automatically bake the behavior tree data if the component is enabled and the behavior tree starts when enabled.

See the EntitySpawner component within the Entity sample scene for a working example.

Lets consider the example where you want to spawn 100 state machines agents using the baked data. The first step is to assign the state machine prefab that should be spawned, and then create a system that runs once. 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 state machine 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 state machine prefab can then be instantiated into a state machine 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.
    }
}