Assigning the same value to all array int elements using for-s Unity C#

Hello,
This is my first time asking.
Why does this not work and says that “Index was outside the bounds of the array.”

for(int i = 0; i < x; i++)
        {
            for(int j = 0; j < y; j++)
            {
                for(int k = 0; k < z; k++)
                {
                    grid[i, j, k] = 0;
                }
            }
        }
    }

This is how i declare my array:

public static int[,,] grid = new int[x, y, z];

Looks fine to me. You should state specifically which line is causing the out of bounds error. I just tried your code, and it initializes fine for me.

 grid[i, j, k] = 0;

this one. I also think it should work. I am using a weird method to give x,y,z their values but if i debug.log any of them they are just normal int values so i doubt that’s the reason.

Your x, y, z probably don’t match up with the actual size of your array. I know you declared your array using those variables, but it’s also a static array and I’m wondering if maybe you’re not modifying them somewhere else or something like that. Debug it with some logging:

int length0 = grid.GetLength(0);
int length1 = grid.GetLength(1);
int length2 = grid.GetLength(2);

Debug.Log($"Grid lengths are: {length0}, {length1}, {length2}. x, y, z, are {x}, {y}, {z}");

for(int i = 0; i < length0; i++)
        {
            for(int j = 0; j < length1; j++)
            {
                for(int k = 0; k < length2; k++)
                {
                    grid[i, j, k] = 0;
                }
            }
        }
    }

So it’s like this in my code

 public static int x;
    public static int y;
    public static int z;
    public static int[,,] grid = new int[x, z, y];
void Start()
    {
x = GameObject.Find("GameFieldCrator").GetComponent<InstantiateField>().x;
        y = GameObject.Find("GameFieldCrator").GetComponent<InstantiateField>().y;
        z = GameObject.Find("GameFieldCrator").GetComponent<InstantiateField>().z;
        for(int i = 0; i < x; i++)
        {
            for(int j = 0; j < z; j++)
            {
                for(int k = 0; k < y; k++)
                {
                    grid[i, j, k] = 0;
                }
            }
}
        }

I even tried changing the values to be just numbers but the error is the same.

If you insert the Debug.Log statement I suggested you will see the issue. But I think your problem is that your grid array is instantiated way before x y and z get their values. So your array is probably of size (0, 0, 0). static elements get instantiated before pretty much anything else in a class. Start() doesn’t run until much later, after an instance is created and often during the next frame after that.

Debug.Log is your friend!

1 Like

Ahhhhh yes that’s just it! I didn’t think, thank you!