Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Outside of bounds error

Discussion in 'Scripting' started by TheOtherUserName, Feb 24, 2021.

  1. TheOtherUserName

    TheOtherUserName

    Joined:
    May 30, 2020
    Posts:
    136
    I copied some numbers from a brackeys tutorial (too lazy to calculate them myself ;-) ) but I get a outside of bounds error at line 21. I dont understand why it should be declared correctly.
    Code (CSharp):
    1. public void GenerateChunkMesh(int widthInUnits, float[,] noise)
    2.     {
    3.         verts = new Vector3[(widthInUnits + 1) * (widthInUnits + 1)];
    4.         tris = new int[widthInUnits * widthInUnits * 6];
    5.  
    6.         for(int y = 0, i = 0; y < widthInUnits; y++)
    7.         {
    8.             for(int x = 0; x < widthInUnits; x++)
    9.             {
    10.                 verts[i] = new Vector3(transform.position.x + x, noise[x, y], transform.position.y + y);
    11.                 i++;
    12.             }
    13.         }
    14.  
    15.         int vert = 0;
    16.         int triangles = 0;
    17.         for (int j = 0; j < verts.Length - 1; j++)
    18.         {
    19.             for (int i = 0; i < verts.Length - 1; i++)
    20.             {
    21.                 tris[triangles + 0] = vert + 0;
    22.                 tris[triangles + 1] = vert + widthInUnits + 2;
    23.                 tris[triangles + 2] = vert + 1;
    24.                 tris[triangles + 3] = vert + 1;
    25.                 tris[triangles + 4] = vert + widthInUnits + 1;
    26.                 tris[triangles + 5] = vert + widthInUnits + 2;
    27.  
    28.                 triangles += 6;
    29.                 vert++;
    30.             }
    31.             vert++;
    32.         }
    33.     }
    Surely I am overseeing something obvious here but I dont get it.
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,520
    Line 17 and line 19 termination comparison quantities are incorrect.

    Line 3 makes the verts array out of the square of
    (widthInUnits+1)


    Line 4 makes the tris array out of a comparably-squared quantity, expanded by 6 for 2 tris per quad.

    So a 9x9 width would be 100 verts, and 81 * 6 tris.

    Then you are iterating 99 verts within another loop iterating 99 verts, so that's why you are spilling beyond the tris array.

    Most likely you want lines 17 and 19 to both continue when the index value is below
    widthInUnits


    Code (csharp):
    1. for (int j = 0; j < widthInUnits; j++)