Search Unity

Best way to sort multiple ComponentDataArray together.

Discussion in 'Entity Component System' started by 5argon, Jun 22, 2018.

  1. 5argon

    5argon

    Joined:
    Jun 10, 2013
    Posts:
    1,555
    For example the archetype is 2 component data, one with an int and one with a float. I can get 2 ComponentDataArray of each type with the same index maps to the same entity.

    If I want to sort so that the int component is by ascending order, but when iterating through ascending order sorted data what I want to use is the float component what should I do?

    If I use CopyTo NativeArray with the int ComponentDataArray and sort it I can only sort one at a time and the matching index will have no meaning in that case. Is there a way to sort one NativeArray and have the other follow its sorted index?

    Injected -> (1, 0.099) (3, 0.077) (2, 0.888)
    Sorted order that I want -> (1, 0.099) (2, 0.888) (3, 0.077)
    float iteration result that I want in order -> 0.099 0.888 0.077
     
    Last edited: Jun 22, 2018
  2. 5argon

    5argon

    Joined:
    Jun 10, 2013
    Posts:
    1,555
    Currently I do it by ComponentDataArray -> CopyTo 2 NativeArray -> ToArray -> Array.Sort(keyArray, array) -> Dispose 2 NativeArray but it looks very cumbersome

    Code (CSharp):
    1.     /// <summary>
    2.     /// Sorted by asceding note position
    3.     /// </summary>
    4.     public (NoteData[] noteDatas, T[] commands) GetSortedCommands<T>() where T : struct, IComponentData
    5.     {
    6.         var cg = GetComponentGroup(new ComponentType[] { ComponentType.ReadOnly<NoteData>(), ComponentType.ReadOnly<T>() });
    7.  
    8.         var nd = cg.GetComponentDataArray<NoteData>();
    9.         var t = cg.GetComponentDataArray<T>();
    10.         NativeArray<NoteData> na1 = new NativeArray<NoteData>(nd.Length, Allocator.Temp);
    11.         NativeArray<T> na2 = new NativeArray<T>(t.Length, Allocator.Temp);
    12.         nd.CopyTo(na1);
    13.         t.CopyTo(na2);
    14.         var a1 = na1.ToArray();
    15.         var a2 = na2.ToArray();
    16.         Array.Sort(a1, a2, new NoteData.AscendingPositionComparer());
    17.         na1.Dispose();
    18.         na2.Dispose();
    19.  
    20.         return (a1, a2);
    21.     }
     
  3. sngdan

    sngdan

    Joined:
    Feb 7, 2014
    Posts:
    1,154
    Not sur I understand, but would you not be able to just store the entity or index position as the result of your sort. This way you can walk over the arrays in the order you want (though the data is not stored/accessed in a linear way)

    Not sure what the use case is, ie size of arrays, frequency of change, how often iterated over...