Skip to content

πŸ’” Breaking the rules

Isadora edited this page Jun 26, 2023 · 3 revisions

This is the not-really-ECS part, but may make your game development way faster.

πŸšͺ State machines

A state machine is pretty much a component with logic. The actual implementation in the game looks more or less like this:

internal class BuyFromShop : StateMachine
{
    public BuyFromShop()
    {
        State(Idle);
    }

    private IEnumerator<Wait> Idle()
    {
        yield return Wait.ForMessage<InteractMessage>();
        yield return GoTo(ShowShop);
    }

    private IEnumerator<Wait> ShowShop()
    {
        while (true)
        {
            yield return Wait.NextFrame;
        }
    }
}

This will be wrapped in a StateMachineComponent<BuyFromShop> component, and you can fetch this component with entity.GetStateMachine(), so you can only have one state machine per entity.

πŸ”” Interactions

This is when an entity wants to send an interaction to another entity. This is a real example of an interaction that adds a child from a prefab to another entity:

public readonly struct AddChildOnInteraction : Interaction
{
    [JsonProperty]
    private readonly AssetRef<PrefabAsset> _child = new();

    [JsonProperty]
    private readonly string? _name = null;

    public AddChildOnInteraction() { }

    public void Interact(World world, Entity interactor, Entity? interacted)
    {
        if (interacted is null)
        {
            return;
        }

        Entity child = _child.Asset.CreateAndFetch(world);
        interacted.AddChild(child.EntityId, _name);
    }
}

πŸ§‘β€πŸ‘§β€πŸ‘¦ Families

This is where ECS libraries are rather obscure about it. We have a family hierarchy, in which entities hold references to other entities (with their id) that are parents or children. A component that will be affected by this hierarchy will inherit from IParentRelativeComponent, so Bang can send notifications whenever the parent component was modified.

If a parent gets destroyed, its children also get destroyed. If a child gets destroyed, the parent will no longer reference them.