Search Unity

[confused]How to write to other enitiy component inside jobs?

Discussion in 'Entity Component System' started by lijianfeng, Aug 29, 2019.

  1. lijianfeng

    lijianfeng

    Joined:
    Sep 8, 2015
    Posts:
    54
    I know it is convenient to write to component of same entity,But I often need to write to component of other entity,sometimes the write target entity's Archetype is the same as the source entity,sometimes not.

    For example,a entity was a bomb,and it use physics to test other role entities wether in it's explosion range,and write to role enities Healthy component to hurt them.I can't find samples code to acomplish this.:(

    Can you give some sample code to do it? thanks!:)
     
  2. RecursiveEclipse

    RecursiveEclipse

    Joined:
    Sep 6, 2018
    Posts:
    298
    Should be something like this.

    Code (CSharp):
    1. struct (your job type) {
    2.     public ComponentDataFromEntity<Health> HealthComponents;
    3.  
    4.     (execute signature) {
    5.         for each entity damaged {
    6.             HealthComponents[entity].Value = (your calculated value)
    7.          }
    8.     }
    9.  
    10.     protected override JobHandle OnUpdate(JobHandle inputDeps) {
    11.         var yourJobTypeHandle = new yourJobType {
    12.             HealthComponents = GetComponentDataFromEntity<Health>(isReadOnly:false);
    13.         }.Schedule(...);
    14.         return yourJobTypeHandle;
    15.     }
    16. }
     
  3. lijianfeng

    lijianfeng

    Joined:
    Sep 8, 2015
    Posts:
    54
    Have you test your code before? I have try this long time ago,it throw :
    InvalidOperationException: MyJob.Data.healty is not declared [ReadOnly] in a IJobParallelFor job. The container does not support parallel writing. Please use a more suitable container type.:eek:
     
  4. lijianfeng

    lijianfeng

    Joined:
    Sep 8, 2015
    Posts:
    54
    When I and [NativeDisableParallelForRestriction] property,It worked! So this is the right way to do it?
     
  5. RecursiveEclipse

    RecursiveEclipse

    Joined:
    Sep 6, 2018
    Posts:
    298
    Actually I'm not sure atm, haven't written a system in a while. It really depends on if another job will read/write that data. Using that with ComponentDataFromEntity is more difficult than writing to an array specific to a single job. Can we see what your job looks like for better recommendations? A safer way is just read that component, then use ecb to set the component.
     
  6. lijianfeng

    lijianfeng

    Joined:
    Sep 8, 2015
    Posts:
    54
    It looks like I can use the ugrly and wired IJobNativeMultiHashMapMergedSharedKeyIndices to handle this thread safely,I think this may be only a temporary way,there will be easy and clear way to handle this situation in the future.:)