Hi ๐
I am following ECS tank tutorial video from DOTS package github in Unity2022.3.22 Entities 1.2. I was trying to use EntityCommandBuffer to set the player tank and to modify each tank color. Here is the code:
public void OnUpdate(ref SystemState state)
{
state.Enabled = false;
var config = SystemAPI.GetSingleton<Config>();
//Unity.Mathematics random
var random = new Random(123);
//Only accepts objects with this component.
var query = SystemAPI.QueryBuilder().WithAll<URPMaterialPropertyBaseColor>().Build();
var ecb = new EntityCommandBuffer(Allocator.Temp);
//Create a query mask to be used later
var queryMask = query.GetEntityQueryMask();
//Cretes an empty array that can store Entities and has specified size
var tanks = new NativeArray<Entity>(config.TankCount, Allocator.Temp);
// Fill in the array with new tank entities based on the TankPrefab
ecb.Instantiate(config.TankPrefab, tanks);
for (int i = 0; i < tanks.Length; i++)
{
var tankInstance = tanks[i];
if (i == 0)
{
ecb.AddComponent<PlayerTankTag>(tankInstance);
ecb.AddComponent<PlayerTankInputComponent>(tankInstance);
}
float4 color = RandomColor(ref random);
ecb.SetComponentForLinkedEntityGroup(tankInstance, queryMask, new URPMaterialPropertyBaseColor { Value = color });
}
ecb.Playback(state.EntityManager);
}
The problem that I am experiencing is that if I call the if (i == 0) ... block first and next call ecb.SetComponentForLinkedEntityGroup(... line the tankInstance object with index [0] doesn't seem to receive the random color (so the player object).
IF i move the if(i==0) code AFTER the ecb.SetComponentForLinkedEntityGroup( it will work as expected setting the color correctly. I don't quite understand why. Is it because the order of operations / commands of the EntityCommandBuffer ?