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

Single Thread iterate over all entities without allocating

Discussion in 'Entity Component System' started by Guedez, Sep 6, 2020.

  1. Guedez

    Guedez

    Joined:
    Jun 1, 2012
    Posts:
    823
    Currently the only way I know to do this is to Query.ToEntityArray() + Query.ToComponentDataArray() and iterate over these NativeArrays, is there any type of Job that lets me do the same without allocating those arrays?
    I want to check which Entity is closest to a Ray, so I need to linearly iterate over them.
     
  2. tertle

    tertle

    Joined:
    Jan 25, 2011
    Posts:
    3,626
    Chunk iteration in an IJob or Job.WithCode
     
    Guedez likes this.
  3. Guedez

    Guedez

    Joined:
    Jun 1, 2012
    Posts:
    823
    I just noticed that
    Query.GetArchetypeChunkIterator() 
    do not allocate. That's exactly what I needed.
    I was somehow expecting it to return a
    NativeArray<ArchetypeChunk>
    for some reason.
     
  4. Guedez

    Guedez

    Joined:
    Jun 1, 2012
    Posts:
    823
    No actually, how do one use
    ArchetypeChunkIterator
    ? I can't figure out what to do with it, in the end I am still allocating with
    CreateArchetypeChunkArray
     
  5. burningmime

    burningmime

    Joined:
    Jan 25, 2014
    Posts:
    845
    Easiest way would be a system.
    .Run()
    instead of
    .Schedule()
    will run it on the main thread.
    Doesn't need to be linear; if you have a ton of entities you can do this in parallel. For example, split into 12 chunks of 100,000 entities, find the closest in each chunk (along with the distance), and then select the one with the smallest distance.
     
    Guedez likes this.
  6. Guedez

    Guedez

    Joined:
    Jun 1, 2012
    Posts:
    823
    It will be about a 100, maybe 200 max, it's for checking if I should display a tooltip or not, all static tooltip sources use an octree, while this system is only for mobile sources like NPCs.

    So there is little to no difference between Schedule().Complete() and Run()? Or maybe Run() is just better?
     
  7. LazyGameDevZA

    LazyGameDevZA

    Joined:
    Nov 10, 2016
    Posts:
    143
    There is a difference between
    Schedule().Complete()
    and
    Run()
    . The former will hand over the work to a worker thread and wait for it to complete. The latter will immediately run the work on the main thread to completion.
     
  8. DreamingImLatios

    DreamingImLatios

    Joined:
    Jun 3, 2017
    Posts:
    3,983
    Run also writes back the captured values as a bonus convenience.