-4

I am trying to make mesh rendering in Unity 3D but the code is supposed to work, Here is what it said: IndexOutOfRangeException: Index was outside the bounds of the array. MeshGen.CreateShape () (at Assets/MeshGen.cs:33) MeshGen.Start () (at Assets/MeshGen.cs:22)

Here is the code:

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

[RequireComponent(typeof(MeshFilter))]
public class MeshGen : MonoBehaviour {

     Mesh mesh;

      Vector3[] vertices;
      int[] triangles;

      public int xSize = 20;
      public int zSize = 20;

    // Start is called before the first frame update
    void Start()
    {
        mesh = new Mesh();
        GetComponent<MeshFilter>().mesh = mesh;

        CreateShape();
        UpdateMesh();
    }
    void CreateShape()
    {
      vertices = new Vector3[(xSize * 1) * (zSize * 1)];

      int i = 0;
      for (int z = 0; z <= zSize; z++)
      {
        for (int x = 0; x <= xSize; x++)
        {
          vertices[i] = new Vector3(x, 0, z);
          i++;
        }
      }

      triangles = new int[xSize * zSize * 6];

      int vert = 0;
      int tris = 0;
      for (int x = 0; x < xSize; x++)
      {
        triangles[tris + 0] = vert + 0;
        triangles[tris + 1] = vert + xSize + 1;
        triangles[tris + 2] = vert + 1;
        triangles[tris + 3] = vert + 1;
        triangles[tris + 4] = vert + xSize + 1;
        triangles[tris + 5] = vert + xSize + 2;

        vert++;
        tris += 6;
      }
    }

  void UpdateMesh()
    {
      mesh.Clear();

      mesh.vertices = vertices;
      mesh.triangles = triangles;

      mesh.RecalculateNormals();
    }

private void OnDrawGizmos()
{
  if (vertices == null)
    {return;}

  for (int i = 0; i < vertices.Length; i++)
  {
    Gizmos.DrawSphere(vertices[i], .1f);
  }
}

}

I tried fixing it, tried searching on google and i made sure that it is right. This was the only error i got.

1 Answers1

0

Let's check this:

public int xSize = 20;
public int zSize = 20;

// array of size 20*20=400 : indexes in range [0:399]
vertices = new Vector3[(xSize * 1) * (zSize * 1)];

int i = 0;
// loop in range [0:20] (21 iterations)
for (int z = 0; z <= zSize; z++)
{
    // loop in range [0:20] (21 iterations)
    for (int x = 0; x <= xSize; x++)
    {
        vertices[i] = new Vector3(x, 0, z);
        i++;
        // after we reach z=18 and x=20, i=399
        // from now on, we are OutOfBounds
    }
}

You should probably switch to strict inequality < instead of <=

Rafalon
  • 4,450
  • 2
  • 16
  • 30
  • This ended up making the issue even worse. I found that I just used * symbol instead of + symbol. – Tadeáš Hrudka Nov 08 '22 at 16:35
  • Ah, I was wondering about that `(xSize * 1) * (zSize * 1)` too and why it wasn't just `xSize * zSize`. Though, if you have `x*y` size, why would you allocate `(x+1)*(z+1)` space and not just `x*z`? – Rafalon Nov 08 '22 at 17:05