Search Unity

Question Getting EntityCommandBuffer with SystemState.GetEntityQuery

Discussion in 'Entity Component System' started by lclemens, Apr 26, 2023.

  1. lclemens

    lclemens

    Joined:
    Feb 15, 2020
    Posts:
    761
    I am trying to fetch an entity command buffer without using the system API (because I need to simplify some code). So I used SystemState.GetEntityQuery() to make a query in OnCreate() so it will be cached and then later in OnUpdate() I used EntityQuery.TryGetSingleton() to fetch the ECB singleton.

    Anyone know why EntityQuery.TryGetSingleton() fails every time? It seems to me like it should work - I can see the singleton exists at runtime in the DOTS inspection tools.

    Code (CSharp):
    1.  
    2.  
    3. public struct MyStruct
    4. {
    5.     EntityQuery m_ecbBeginQuery;
    6.  
    7.     void MyStruct(ref SystemState state)
    8.     {
    9.          m_ecbBeginQuery = state.GetEntityQuery(typeof(BeginSimulationEntityCommandBufferSystem.Singleton));
    10.     }
    11.  
    12.     public void CalculateCount() { return m_ecbBeginQuery.CalculateEntityCount();
    13.  
    14.     public bool TestGetSingleton()
    15.     {
    16.           return m_ecbBeginQuery.TryGetSingleton<BeginSimulationEntityCommandBufferSystem.Singleton>(out BeginSimulationEntityCommandBufferSystem.Singleton ecbBeginSingleton);
    17.     }
    18. }
    19.  
    20. [BurstCompile]
    21. public partial struct MySystem : ISystem
    22. {
    23.     MyStruct m_myStruct;
    24.  
    25.     void OnCreate(ref SystemState state)
    26.     {
    27.         // cache the entity query
    28.         m_myStruct = new MyStruct(ref state);
    29.     }
    30.  
    31.     [BurstCompile]
    32.     void OnUpdate(ref SystemState state)
    33.     {
    34.         // this always returns zero... why?
    35.         int count = m_myStruct.CalculateCount();
    36.  
    37.         // this always returns false... why?
    38.         bool exists = m_myStruct.TestGetSingleton();
    39.     }
    40. }
    41.  
     
    Last edited: Apr 26, 2023
  2. tertle

    tertle

    Joined:
    Jan 25, 2011
    Posts:
    3,761
    It's because the singleton is added to the SystemHandle so you need
    WithOptions(EntityQueryOptions.IncludeSystems)
     
    lclemens likes this.
  3. Dainofel

    Dainofel

    Joined:
    Oct 12, 2019
    Posts:
    35
    Where would you add your suggestion, Tertle? I had the same problem a while ago and I couldn't solve it. Knowing how to fetch and handle a ecb on iSystem would be really useful.
     
  4. tertle

    tertle

    Joined:
    Jan 25, 2011
    Posts:
    3,761
    On the query builder, either SystemAPI or manual one or on your EntityQueryDesc Options field

    SystemAPI.QueryBuilder().WithAll<EndSimulationEntityCommandBufferSystem.Singleton>().WithOptions(EntityQueryOptions.IncludeSystems).Build()
     
    lclemens likes this.