Search Unity

2D Array with burst - is the following a valid approach or will that cause trouble down the road?

Discussion in 'Burst' started by AurelWu, May 1, 2019.

  1. AurelWu

    AurelWu

    Joined:
    Oct 11, 2013
    Posts:
    26
    I'm experimenting around and don't really completely understand everything yet so I'd appreciate if someone more knowledgeable could tell me if the following approach is safe&sane:

    Code (CSharp):
    1. public struct Fast2DArray<T> : System.IDisposable where T: struct
    2. {
    3.     private int sizeX;
    4.     private NativeArray<T> flatArray;
    5.  
    6.  
    7.     public Fast2DArray(int sizeX, int sizeY, Allocator allocator)
    8.     {
    9.         this.sizeX = sizeX;
    10.         flatArray = new NativeArray<T>(sizeX * sizeY, allocator);
    11.     }
    12.  
    13.     public T this[int x, int y]
    14.     {
    15.         get { return flatArray[x + y * sizeX]; }
    16.         set { flatArray[x + y * sizeX] = value; }
    17.     }
    18.  
    19.     public void Dispose()
    20.     {
    21.         flatArray.Dispose();
    22.     }
    23. }
    It seems to work and is very quick from what I benchmarked, but I might be missing something so I feel rather insecure about it.
     
    stroibot likes this.
  2. Xerioz

    Xerioz

    Joined:
    Aug 13, 2013
    Posts:
    104
    Looks good, just make sure to add some boundary checks in case
    x + y * sizeX
    is smaller than 0 or bigger than array's max length
     
    AurelWu likes this.