Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

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

Discussion in 'Entity Component System' started by eneIr, Jul 23, 2020.

  1. eneIr

    eneIr

    Joined:
    Nov 28, 2018
    Posts:
    15
    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<T> 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<T> in a system please.
     
  2. davenirline

    davenirline

    Joined:
    Jul 7, 2010
    Posts:
    944
    You can't use vanilla ComponentDataFromEntity<T> 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<T> 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.
     
    eneIr likes this.
  3. yondercode

    yondercode

    Joined:
    Jun 11, 2018
    Posts:
    27
    You can also disable the parallel for restriction in lambda job using
    .WithNativeDisableParallelForRestriction(variable)
     
    eneIr and davenirline like this.