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

Why the "_buffer" in CleanupSystem only call once, but it's not empty? #954

Closed atkdefender closed 3 years ago

atkdefender commented 3 years ago
readonly List<GameEntity> _buffer = new List<GameEntity>();

...

foreach (var e in _group.GetEntities(_buffer)) { //the only call
    Debug.Log(_buffer.Count); //Print:1
    e.Destroy();
}
rglobig commented 3 years ago

The buffer is there to prevent the GetEntities method from allocating. After or before use you should clean up your buffers using the _buffer.Clear() method. This way you can make sure that you always have a new buffer and no unnecessary data is allocated on the heap that is collected by the garbage collector.

atkdefender commented 3 years ago

The buffer is there to prevent the GetEntities method from allocating. After or before use you should clean up your buffers using the _buffer.Clear() method. This way you can make sure that you always have a new buffer and no unnecessary data is allocated on the heap that is collected by the garbage collector.

Thx for the answer. Your answer is about "what for" and "how to use". I want to ask "how it works": Sorry about I don't ask the question correctly.

The _buffer is readonly, it only call by _group.GetEntities(_buffer), as a param. Then which part of the program, put a GameEntity inside the _buffer?

public sealed class DestroyDestroyedGameSystem : ICleanupSystem
{
    readonly IGroup<GameEntity> _group;
    readonly List<GameEntity> _buffer = new List<GameEntity>();

    public DestroyDestroyedGameSystem(Contexts contexts)
    {
        _group = contexts.game.GetGroup(GameMatcher.Destroyed);
        Debug.Log("CCC="+_buffer.Count); //Print:CCC=0
    }

    public void Cleanup()
    {
        foreach (var e in _group.GetEntities(_buffer))
        {
            Debug.Log(_buffer.Count); //Print:1
            e.Destroy();
        }
    }
}
sschmid commented 3 years ago

_group.GetEntities(_buffer) will clear your buffer, add all entities of the group and will return the buffer for convenience and nice syntax.

See https://github.com/sschmid/Entitas-CSharp/blob/master/Entitas/Entitas/Group/Group.cs#L153-L158

atkdefender commented 3 years ago

_group.GetEntities(_buffer) will clear your buffer, add all entities of the group and will return the buffer for convenience and nice syntax.

See https://github.com/sschmid/Entitas-CSharp/blob/master/Entitas/Entitas/Group/Group.cs#L153-L158

I got it. So the readonly still can be modify. Thx for the answer :D