IndexOutOfRangeException: Index out of bounds of the Array?

Hi, it is me again. So I recieved this error with my code:
IndexOutOfRangeException: Index was outside the bounds of the array.
Chunk.CheckVoxel (UnityEngine.Vector3 pos) (at Assets/Scripts/C#/Chunk.cs:59)
Chunk.AddVoxelDataToChunk (UnityEngine.Vector3 pos) (at Assets/Scripts/C#/Chunk.cs:64)
Chunk.CreateMeshData () (at Assets/Scripts/C#/Chunk.cs:45)
Chunk.Start () (at Assets/Scripts/C#/Chunk.cs:22)

I have looked at my code here:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Chunk : MonoBehaviour
{
    public MeshRenderer meshRenderer;
    public MeshFilter meshFilter;
   
    int vertexIndex = 0;
    List<Vector3> vertices = new List<Vector3> ();
    List<int> triangles = new List<int> ();
    List<Vector2> uvs = new List<Vector2> ();
   
    byte[,,] voxelMap = new byte[VoxelData.ChunkWidth, VoxelData.ChunkHeight, VoxelData.ChunkWidth];
   
    World world;
   
    void Start () {
        world = GameObject.Find("World").GetComponent<World>();
        PopulateVoxelMap ();
        CreateMeshData ();
        CreateMesh ();
    }
   
    void PopulateVoxelMap () {
        for (int y = 0; y < VoxelData.ChunkHeight; y++) {
            for (int x = 0; x < VoxelData.ChunkWidth; x++) {
                for (int z = 0; z < VoxelData.ChunkWidth; z++) {
                        if (y < 1)
                            voxelMap[x, y, z] = 0;
                        else if (y == VoxelData.ChunkHeight - 1)
                            voxelMap[x, y, z] = 3;
                        else
                            voxelMap[x, y, z] = 1;
                }
            }
        }
    }
   
    void CreateMeshData () {
        for (int y = 0; y < VoxelData.ChunkHeight; y++) {
            for (int x = 0; x < VoxelData.ChunkWidth; x++) {
                for (int z = 0; z < VoxelData.ChunkWidth; z++) {
                        AddVoxelDataToChunk (new Vector3(x, y, z));
                }
            }
        }
    }
   
    bool CheckVoxel (Vector3 pos) {
        int x = Mathf.FloorToInt (pos.x);
        int y = Mathf.FloorToInt (pos.y);
        int z = Mathf.FloorToInt (pos.z);
       
        if (x < 0 || x > VoxelData.ChunkWidth - 1 || y < 0 || y > VoxelData.ChunkHeight - 1 || z < 0 || z > VoxelData.ChunkWidth - 1) {
            return false;
        }
        return world.blocktypes[voxelMap[x, y, z]].isSolid;
    }
   
    void AddVoxelDataToChunk (Vector3 pos) {
        for (int p = 0; p < 6; p++) {
            if(!CheckVoxel(pos + VoxelData.faceChecks[p])) {
                byte blockID = voxelMap[(int)pos.x, (int)pos.y, (int)pos.z];
                vertices.Add (pos + VoxelData.voxelVerts [VoxelData.voxelTris [p, 0]]);
                vertices.Add (pos + VoxelData.voxelVerts [VoxelData.voxelTris [p, 1]]);
                vertices.Add (pos + VoxelData.voxelVerts [VoxelData.voxelTris [p, 2]]);
                vertices.Add (pos + VoxelData.voxelVerts [VoxelData.voxelTris [p, 3]]);
                AddTexture(world.blocktypes[blockID].GetTextureID(p));
                triangles.Add (vertexIndex);
                triangles.Add (vertexIndex + 1);
                triangles.Add (vertexIndex + 2);
                triangles.Add (vertexIndex + 2);
                triangles.Add (vertexIndex + 1);
                triangles.Add (vertexIndex + 3);
                vertexIndex += 4;
            }
        }
    }
   
    void CreateMesh () {
        Mesh mesh = new Mesh ();
        mesh.vertices = vertices.ToArray ();
        mesh.triangles = triangles.ToArray ();
        mesh.uv = uvs.ToArray ();
       
        mesh.RecalculateNormals ();
       
        meshFilter.mesh = mesh;
    }
   
    void AddTexture (int textureID) {
        float y = textureID / VoxelData.TextureAtlasSizeInBlocks;
        float x = textureID % VoxelData.TextureAtlasSizeInBlocks;
       
        x *= VoxelData.NormalizedBlockTextureSize;
        y *= VoxelData.NormalizedBlockTextureSize;
       
        y = 1f - y - VoxelData.NormalizedBlockTextureSize;

        uvs.Add (new Vector2(x, y));
        uvs.Add (new Vector2(x, y + VoxelData.NormalizedBlockTextureSize));
        uvs.Add (new Vector2(x + VoxelData.NormalizedBlockTextureSize, y));
        uvs.Add (new Vector2(x + VoxelData.NormalizedBlockTextureSize, y + VoxelData.NormalizedBlockTextureSize));
    }
}

And here is my voxel Data Script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class VoxelData
{
    public static readonly int ChunkWidth = 5;
    public static readonly int ChunkHeight = 15;
    public static readonly int TextureAtlasSizeInBlocks = 4;
   
    public static float NormalizedBlockTextureSize {
        get { return 1f / (float)TextureAtlasSizeInBlocks; }
    }
   
    public static readonly Vector3[] voxelVerts = new Vector3[8] {
        // Represents Location of Vertices in the Cube (Voxel)
        new Vector3(0.0f, 0.0f, 0.0f),
        new Vector3(1.0f, 0.0f, 0.0f),
        new Vector3(1.0f, 1.0f, 0.0f),
        new Vector3(0.0f, 1.0f, 0.0f),
        new Vector3(0.0f, 0.0f, 1.0f),
        new Vector3(1.0f, 0.0f, 1.0f),
        new Vector3(1.0f, 1.0f, 1.0f),
        new Vector3(0.0f, 1.0f, 1.0f),
    };
   
    public static readonly Vector3[] faceChecks = new Vector3[6] {
        new Vector3(0.0f, 0.0f, -1.0f),
        new Vector3(0.0f, 0.0f, 1.0f),
        new Vector3(0.0f, 1.0f, 0.0f),
        new Vector3(0.0f, -1.0f, 0.0f),
        new Vector3(-1.0f, 0.0f, 0.0f),
        new Vector3(1.0f, 0.0f, 0.0f),
    };
   
    public static readonly int[,] voxelTris = new int[6,4] {
        // Represents the Voxel Triangle Faces
        // 0 1 2 2 1 3
        {0, 3, 1, 2}, // Back Face
        {5, 6, 4, 7}, // Front Face
        {3, 7, 2, 6}, // Top Face
        {1, 5, 0, 4}, // Bottom Face
        {4, 7, 0, 3}, // Left Face
        {1, 2, 5, 6}, // Right Face
    };
   
    public static readonly Vector2[] voxelUvs = new Vector2[4] {
        new Vector2 (0.0f, 0.0f),
        new Vector2 (0.0f, 1.0f),
        new Vector2 (1.0f, 0.0f),
        new Vector2 (1.0f, 1.0f),
    };
}

I was using a tutorial and referencing his scripts but it appears I have reached an issue. I am sure I missed something but I haven’t been able to find where I messed up.

Here is where the YouTube Content Creators scripts are:

So did I miss something or is the problem elsewhere? I have one other script but I doubt it is in there.

Thanks ahead of time.

If line 59 in the first script is where you are getting the error, I see that it contains two nested dereferences.

First you get the Voxel x,y,z, which is perhaps okay since you guard it beforehand, but then you use the value to unquestioningly dereference another list of blocktypes.

Like any engineering problem, the first step is to break it apart: use an intermediate integer, then print it out with Debug.Log(), and see why it is exceeding bounds. And if it isn’t then check the x,y,z by printing them out.

Thanks I will try that.

1 Like

Okay

So I used Debug.Log and it said 515 but since I was trying to make it a byte the code would work. This is because bytes can only store up to 255 right? Or am I way off subject?

Bytes do indeed only store 0 to 255… not sure how you are seeing 515… what exactly are you printing, the contents of the voxelMap[,,] array at that point?

I

Just realized where I messed up on the Debug Log the reason it said 515 is because there wasn’t a space between the two separate values. I was printing the VoxelData.ChunkWidth and VoxelData.ChunkHeight.

So the command read:
Debug.Log("Checking: " + VoxelData.ChunkWidth + VoxelData.ChunkHeight);

So what it meant to say was 5 15

Whew, I was starting to suspect you were using some new-fangled byte that had like 10 or more bits. :slight_smile: I was gonna ask you where you got those! They sound useful…

Seriously, just stick a + "," + in there and off you go.

Also, don’t bother printing those two values, they’re marked as readonly and hence constants. It’s the resulting dereferenced value you want, what you use to look up the chunk type or whatever it was called. Or the x,y,z values… those are where the bad value is.

Lol

So I fixed the command and now the console says “Checking: 5,15”.

As my post noted above, those values are constants. There’s no point in printing them out. It’s like asking what time the 6pm train departs.

Print out values that contain actual data, such as x,y,z and also voxelMap[x,y,z]

That’s when you’re gonna learn some really interesting stuff.

So I think I did this correctly, I am not sure but here goes I typed:
Debug.Log("Checking: " + voxelMap[x, y, z]);
And it x, y, z does not exist in the current context. Sorry I am pretty new to Unity.

Is the error happening in line 59 of the script as numbered above? Because if it is, that context certainly exists.

If it is not, just print out EVERY value immediately before the line where the error happened. This is basic debugging steps.

So I put the code before the line with the error. And I got some new errors. 9 to be exact.

Invalid token ‘(’
Type Expected
Tuple must contain at least two elements
) expected
Invalid token "Checking: " in class…
Array size cannot be specified in a variable declaration occured 3 times
Invalid token ‘)’

My bad

I put it in wrong spot, now it says Checking 0
Checking 1

I am having the same problem with the same code
please help

This exception means that you’re trying to access a collection item by index, using an invalid index. An index is invalid when it’s lower than the collection’s lower bound or greater than or equal to the number of elements it contains. Indexing an empty list will always throw an exception. Use a method like Add to append the item to the end of the list, or Insert to place the item in the middle of the list somewhere, etc. You cannot index into a list if that offset doesn’t exist. IndexOutOfRangeException exception is thrown as a result of developer error. Instead of handling the exception, you should diagnose the cause of the error and correct your code.

did anybody find a fix to this

Finish the episode 4 (the next one) and you will not have the error any more. Me it’s that I do and it’s work.