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

How to check if the result of an EntityQuery has changed

Discussion in 'Entity Component System' started by SimonCVintecc, Jul 31, 2020.

  1. SimonCVintecc

    SimonCVintecc

    Joined:
    Jun 4, 2019
    Posts:
    8
    I'm using an EntityQuery to fetch component data from entities, in order to use this data in a job.
    However, in my application, the component data fetched this way rarely changes.

    It would be more efficient to only fetch the component data when the results of the entity query have actually changed (instead of every fame in the OnUpdate() method).

    Is there a way to check if the results of the entity query have changed?
    (one way to do this would be to check query.CalculateEntityCount(), but this would not work when adding and removing an entity that conforms to the query in a single frame...)

    Current code example:
    Code (CSharp):
    1. protected override void OnUpdate()
    2. {
    3.     var query = GetEntityQuery(ComponentType.ReadOnly<MyComponentData>());
    4.     var data = query.ToComponentDataArray<MyComponentData>(Allocator.TempJob);
    5.        
    6.     // .. do stuff with data, dispose data after having used it
    7. }

    Desired code example:
    Code (CSharp):
    1. private NativeArray<MyComponentData> data;
    2.  
    3. protected override void OnUpdate()
    4. {
    5.     var query = GetEntityQuery(ComponentType.ReadOnly<MyComponentData>());
    6.  
    7.     if(query.HasChanged()) //<<< does something like this exist?
    8.     {
    9.          data.Dispose();
    10.          data = query.ToComponentDataArray<MyComponentData>(Allocator.Persistent);
    11.     }
    12.      
    13.     // .. do stuff with data, dispose data on system disposal
    14. }
     
  2. RoughSpaghetti3211

    RoughSpaghetti3211

    Joined:
    Aug 11, 2015
    Posts:
    1,695
    I guess all you have to do is check the query count?
     
  3. brunocoimbra

    brunocoimbra

    Joined:
    Sep 2, 2015
    Posts:
    677
    I think you are looking for the Add/SetChangedVersionFilter method
     
  4. SimonCVintecc

    SimonCVintecc

    Joined:
    Jun 4, 2019
    Posts:
    8
    That looks interesting, thanks!