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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Using Physics inside SystemBase - dependency issue

Discussion in 'Entity Component System' started by meanfox, May 20, 2020.

  1. meanfox

    meanfox

    Joined:
    Apr 9, 2020
    Posts:
    25
    When I run this code:

    Code (CSharp):
    1. using UnityEngine;
    2. using Unity.Entities;
    3. using Unity.Physics;
    4. using Unity.Physics.Systems;
    5. using Unity.Jobs;
    6. using Unity.Mathematics;
    7.  
    8. [UpdateAfter(typeof(BuildPhysicsWorld))]
    9. public class SystemGun : SystemBase
    10. {
    11.     protected override void OnUpdate()
    12.     {
    13.         var physicsWorldSystem = World.GetOrCreateSystem<BuildPhysicsWorld>();
    14.         var collisionWorld = physicsWorldSystem.PhysicsWorld.CollisionWorld;
    15.  
    16.         Dependency = JobHandle.CombineDependencies(Dependency, physicsWorldSystem.FinalJobHandle);
    17.  
    18.         Entities.ForEach((ref ComponentGun componentGun, ref ComponentPower componentPower) =>
    19.         {
    20.             var filter = new CollisionFilter
    21.             {
    22.                 BelongsTo = 1u << 2, // bullets
    23.                 CollidesWith = 1u << 1, // enemies
    24.             };
    25.  
    26.             var input = new PointDistanceInput
    27.             {
    28.                 Position = float3.zero,
    29.                 MaxDistance = 10,
    30.                 Filter = filter
    31.             };
    32.  
    33.             if (collisionWorld.CalculateDistance(input, out DistanceHit closestHit))
    34.             {
    35.                 // do stuff
    36.             }
    37.         }).ScheduleParallel();
    38.     }
    39. }
    I get this error:

    InvalidOperationException: The previously scheduled job SystemGun:<>c__DisplayClass_OnUpdate_LambdaJob0 writes to the NativeArray <>c__DisplayClass_OnUpdate_LambdaJob0.JobData.collisionWorld.m_Bodies. You are trying to schedule a new job SystemCollisions:CollisionEventImpulseJob, which reads from the same NativeArray (via CollisionEventImpulseJob.EventReader.m_Bodies). To guarantee safety, you must include SystemGun:<>c__DisplayClass_OnUpdate_LambdaJob0 as a dependency of the newly scheduled job.


    Erm what?

    Can anyone advise how to fix this up using this ForEach job format?

    Thanks!
     
  2. meanfox

    meanfox

    Joined:
    Apr 9, 2020
    Posts:
    25
  3. meanfox

    meanfox

    Joined:
    Apr 9, 2020
    Posts:
    25
    Think I found the proper way to do it:

    }).WithReadOnly(collisionWorld).ScheduleParallel();
     
    kro11 likes this.