sschmid / Entitas

Entitas is a super fast Entity Component System (ECS) Framework specifically made for C# and Unity
MIT License
7.08k stars 1.11k forks source link

When we store a gameEntity's id, instead of a gameEntity? #958

Closed atkdefender closed 3 years ago

atkdefender commented 3 years ago

I find some codes in my project. I use comtext.game.SubscribeId(id) many times, but I don't know why.

[Game, Input, Debug]  // contexts here
public class IdComponent : IComponent
{
    [PrimaryEntityIndex]
    public int value;
}

public static class ContextsIdExtensions
{
    public static void SubscribeId(this Contexts contexts)
    {
        foreach (var context in contexts.allContexts)
        {
            if (Array.FindIndex(context.contextInfo.componentTypes, v => v == typeof(IdComponent)) >= 0)
            {
                context.OnEntityCreated += AddId;
            }
        }
    }

    public static void AddId(IContext context, IEntity entity)
    {
        (entity as IIdEntity).ReplaceId(entity.creationIndex);
    }
}