Search Unity

Sorting a DynamicBuffer

Discussion in 'Entity Component System' started by AndesSunset, Feb 7, 2019.

  1. AndesSunset

    AndesSunset

    Joined:
    Jan 28, 2019
    Posts:
    60
    Hello!

    I'm wondering if there's a built in API, or standard approach to sorting a DynamicBuffer.

    If there isn't, here are the existing options I'm aware of:

    1.Convert DynamicBuffer to NativeArray -> Sort the NativeArray -> Assign values back to DynamicBuffer.
    2. Write your own
    Sort<T>()
    or
    OrderBy<T>()
    extension for DynamicBuffer, which mimics .Net Sorting logic.

    #2 Sounds fine, though I'd worry I could be clumsily stomping on Unity's design intentions for DBs.

    Please sound off if you have better ideas. :)
     
    Last edited: Feb 7, 2019
  2. elcionap

    elcionap

    Joined:
    Jan 11, 2016
    Posts:
    138
    DynamicBuffer has a AsNativeArray method and NativeArray has a Sort method that accept, IIRC, a IComparer implementation:

    Code (CSharp):
    1. public struct RaycastHitDistanceComparer : IComparer<RaycastHit> {
    2.     public int Compare(RaycastHit lhs, RaycastHit rhs) {
    3.         return lhs.distance.CompareTo(rhs.distance);
    4.     }
    5. }
    6.  
    7. DynamicBuffer<Foo> myBuffer;
    8. var hits = myBuffer.AsNativeArray();
    9.  
    10. hits.Sort(new RaycasthHitDistanceComparer());
    You can implement IComparer<T>, Comparer<T> or use Comparer<T>.Create.

    []'s
     
  3. AndesSunset

    AndesSunset

    Joined:
    Jan 28, 2019
    Posts:
    60
    Thanks! That's #1, from the OP:

    I'm concerned about unnecessary work here, that could have a (tiny, but cumulative) performance impact. It would be nice if we didn't have to create a new collection, sort it, make a bunch of assignments back to the DB, and then dispose of the middleman collection.
     
  4. recursive

    recursive

    Joined:
    Jul 12, 2012
    Posts:
    669
    You don't have to worry about it.
    AsNativeArray()
    only creates a shadow copy to the actual
    DynamicBuffer
    contents, not a copy of the data.
     
    rigidbuddy and AndesSunset like this.
  5. AndesSunset

    AndesSunset

    Joined:
    Jan 28, 2019
    Posts:
    60
    Oh, rad! ...hmm, based on the way NativeCollections work, I should have guessed as much. :p

    OK, well then that basically covers it. Thank you. :)
     
    Last edited: Feb 7, 2019
    recursive likes this.
  6. elcionap

    elcionap

    Joined:
    Jan 11, 2016
    Posts:
    138
    You don't need it, it's not a copy.
    The NativeArray returned by AsNativeArray points to the same address of the DynamicBuffer.

    []'s
     
    AndesSunset likes this.