Can someone show me how to use ComponentDataFromEntity<T> correctly.

I’m still a novice in writing ecs code and I just watch tutorial videos on youtube to learn but those all are quite dated now. I used ComponentDataFromEntity in my code and in the console it kept showing the error which is “InvalidOperationException: <>c__DisplayClass_OnUpdate_LambdaJob0.JobData.datas is not declared [ReadOnly] in a IJobParallelFor job. The container does not support parallel writing. Please use a more suitable container type”. Can anyone show me some right example using ComponentDataFromEntity in a system please.

You can’t use vanilla ComponentDataFromEntity in parallel. Use Schedule() in your ForEach(). Another way is to add WithReadOnly(componentDataFromEntity) description to your ForEach().

Optionally, you could also create the struct job yourself. You can then set the attribute [NativeDisableParallelForRestriction] to the ComponentDataFromEntity variable. This is kind of a hack. You have to make sure that no more than a single thread will read/write an item in ComponentDataFromEntity. If you’re only reading from your ComponentDataFromEntity, then add the [ReadOnly] attribute so you can safely use it with parallel threads.

1 Like

You can also disable the parallel for restriction in lambda job using .WithNativeDisableParallelForRestriction(variable)

2 Likes