Search Unity

Adding/Removing components with ForEach

Discussion in 'Entity Component System' started by kork, Mar 15, 2019.

  1. kork

    kork

    Joined:
    Jul 14, 2009
    Posts:
    280
    So ForEach is the new kid in town for doing chunk iteration in a simple way. And it works reasonably well if all you do is modify component values. However I quite often have the requirement to add or remove components:

    Code (CSharp):
    1. public void OnUpdate() {
    2.     ForEach(entity -> {
    3.         PostUpdateCommands.AddComponent(entity, new SomeComponent());
    4.    }, someComponentGroup);
    5. }
    This works however it creates an allocation for `this` all the time. Currently I solve this by doing manual chunk iteration, but this is creating really noisy code with those nested `foreach` loops and the other boilerplate that is required for chunk iteration. Is there a better way of doing this?