Search Unity

Multi-Dimensional Array to Single-Dimensional Index math help

Discussion in 'Scripting' started by MongooseJV, Feb 18, 2017.

  1. MongooseJV

    MongooseJV

    Joined:
    Feb 25, 2014
    Posts:
    20
    Since we cannot serialize multi-dimensional arrays we are limited to using one dimensional arrays along with math to convert from x,y pairs to an index and back out. Here are the current conversion algorithms:

    Code (CSharp):
    1. int Width = 3; // Number of cells along the x axis
    2. int Height = 3; // Number of cells along the y axis
    3.  
    4. GameObject[] Cells = new GameObject[ Width * Height ];
    5.  
    6. public int CalculateIndex( int x, int y )
    7. {
    8.     return y * Width + x;
    9. }
    10.  
    11. public void CalculateXY(int i, out x, out y)
    12. {
    13.     x = i % Width;
    14.     y = i / Width;
    15. }
    Now, I have the problem where I need to create a 3 dimensional grid which introduces Depth as well as the z axis but I can't figure out how to inject the changes into the methods above... I'm having a mental block. Please help me on my endeavor.

    -jv
     
  2. Fabian-Haquin

    Fabian-Haquin

    Joined:
    Dec 3, 2012
    Posts:
    231