unity-game-engineunity-dotsunity-ecs

Unity ECS - How to modify the element of a DynamicBuffer


I have this piece of code:

foreach (DynamicBuffer<Items> items in SystemAPI.Query<DynamicBuffer<Items>>())
{
   ...
}

I am trying to modify a specific element of items. This is how I am trying to achieve this: items[3] = modifiedItem;

But I get the error

Cannot modify members of 'items' because it is a 'foreach iteration variable'.

How can I modify the elements of items?


Solution

  • Type DynamicBuffer<T> is a valuetype, usually it is meaningless to modify the foreach iteration variable of valuetype, so it's forbidden in C#. You can assign this variable to another variable to bypass this layer of restriction:

    foreach (DynamicBuffer<Items> items in SystemAPI.Query<DynamicBuffer<Items>>())
    {
       var items2 = items;
       items2[3] = modifiedItem;
    }