Search Unity

TriggerEvents and CollisionEvents, How To Use Them

Discussion in 'Physics for ECS' started by marcuslelus, Apr 10, 2020.

  1. marcuslelus

    marcuslelus

    Joined:
    Jun 18, 2018
    Posts:
    67
    In Unity's [Physics 0.3.0-preview.1] changelog, it states:

    Added the following new types:
    • CollisionEvents (allows iterating through events directly using a foreach loop, rather than only via ICollisionEventsJob)
    • TriggerEvents (allows iterating through events directly using a foreach loop, rather than only via ITriggerEventsJob)

    My project team and I managed to use TriggerEvents like so, though it seems really sketchy.

    Code (CSharp):
    1.    protected override void OnUpdate()
    2.     {
    3.         //Debug.Log("Simulation Type: " + stepPhysicsWorld.Simulation.GetType());
    4.         var events = ((HavokSimulation) stepPhysicsWorld.Simulation).TriggerEvents;
    5.  
    6.         var getter = GetComponentDataFromEntity<BulletTag>();
    7.      
    8.         Stack<Entity> toDelete = new Stack<Entity>();
    9.      
    10.         foreach (var i in events)
    11.         {
    12.             if (getter.Exists(i.Entities.EntityB))
    13.             {
    14.                 toDelete.Push(i.Entities.EntityB);
    15.             }
    16.         }
    17.  
    18.         foreach (Entity entity in toDelete)
    19.         {
    20.             entityManager.DestroyEntity(entity);
    21.         }
    22.      
    23.         toDelete.Clear();
    24.     }
    So here's my questions. What is the right way to iterate through TriggerEvents and CollisionEvents using the most updated ways of DOTS (SystemBase, Entities.Foreach, no Job struct....)?

    Thanks
     
    Last edited: Apr 10, 2020
    Trypants and nanobot_games like this.
  2. petarmHavok

    petarmHavok

    Joined:
    Nov 20, 2018
    Posts:
    461
    Yeah, using the foreach approach to iterate events unfortunately requires you to know the exact simulation type at the moment. If you would like to avoid that, please use the ICollisionEventsJob and ITriggerEventsJob, they seem fine for your use case as you are collecting some entities to delete. Just implement their interface and schedule them any time after the physics step and before EndFramePhysicsSystem.
     
    Trypants and brunocoimbra like this.