- Home /
Access a multidimensional array inside an array
Hey all,
I am working on a voxel engine and I have an array of chunks, which is actually just a 4dimensional array of blocks. The first index in the array is a chunk index and the rest are the x, y and z indexes of the blocks inside the chunks. Now I would like to loop through all the chunk indexes and pass the 3 dimensional array inside the chunks to a method, but it gives me an error. Here is an example:
Block[,,,] blockData = new Block[chunkIndexes.Length, chunkSizeX, chunkSizeY, chunkSizeZ];
for (int i = 0; i < chunkIndexes.Length; ++i)
{
// Here I would like to pass the 3dimensional array to a method but it gives
// me an error saying that blockData requires 4 indexes.
DoSomeyhingWithTheChunk(blockData[i]);
}
I want to avoid using a List or something like that, does anyone know how i can achieve passing the 3dimensional arrays to a method?
I seem to remember that 2+dimensional arrays need the GetLength[n] command ins$$anonymous$$d of just Length. n is the dimension you are referencing. Hope that helps.
Answer by Seregon · Nov 20, 2013 at 07:32 PM
I don't know of any way of doing exactly what you'd like to in c#, you could probably write a method for cutting up an array like that, but it would involve effectively copying bits of the array, which is rather inefficient.
The closest solution (other than a List
) would be an array of arrays:
Block[][,,] blockData = new Block[chunkIndexes.Length][,,];
for(int i = 0; i < chunkIndexes.Length; i++)
{ Block[i] = new Block[chunkSizeX, chunkSizeY, chunkSizeZ]; }
for (int i = 0; i < chunkIndexes.Length; ++i)
{
// Here I would like to pass the 3dimensional array to a method but it gives
// me an error saying that blockData requires 4 indexes.
DoSomeyhingWithTheChunk(blockData[i]); }
Alternatively, you could pass the block index into the function as an argument, and have the function only operate on the that block, while passing it the entire array as a parameter.