Index was outside of the bounds of the array

im having trouble figering out where this error is coming from in here can anyone see whats going wrong.

public int xSize, ySize;
Vector3[ ] Vertexs;
int[ ] Triangles;
Mesh mesh;
private void Awake()
{
mesh = GetComponent().mesh;
Generate();
}
void Generate()
{
Vertexs = new Vector3[(xSize +1 * ySize + 1)];
/Triangles = new int[xSizeySize * 6];/
for (int i = 0, x = 0; x <= xSize; x++)
{
for(int y = 0; y <= ySize; y++, i++)
{
Vertexs = new Vector3(x, 0, y);
}
}
/*for (int x = 0; x <= xSize; x++)
{
for(int y = 0; y <= ySize; y++)
{
Triangles[0] = 0;
Triangles[1] = 1;
Triangles[2] = 2;
Triangles[3] = 2;
Triangles[4] = 1;
Triangles[5] = 3;
}
_}
/_
mesh.vertices = Vertexs;
mesh.triangles = Triangles;
}
part of the script has been committed out to try and isolate the issue but that hasn’t made it any easier to fined the error.
Thanks Chris

Use code tags and post the error or what line the error is pointing to. Otherwise, it’s just a guess. Since I see you setting values in Triangles, are you sure you have an array of at least size 6?

Actually, this line

Vertexs = new Vector3(x, 0, y);

Doesn’t look right either. Vertexs is an array of Vector3, but you’re trying to assign a single Vector3 to it, is it not throwing an error?

Check the first post in the forum for how to format your code here to be readable.

As for the problem, insert some Debug.Log() statements. At a bare minimum, print the following:

Vertexs.Length
Triangles.Length

(do that right after you allocate them)

Also, your code cannot possible compile, as you are assigning a Vector3 to a Vector3[ ], so check your error logs and fix 'em before you do anything else.

If you want some working examples of fabricating geometry in Unity, check out my makegeo library. It’s got a bunch of random ways of doing stuff, making spheres and planes and whatnot.

MakeGeo is presently hosted at these locations:

https://bitbucket.org/kurtdekker/makegeo

i’ve figured it out, i’m quite embarrassed, a simple math error i forgot to add the ()
Vertexs = new Vector3[(xSize +1 * ySize + 1)];
it should have been
Vertexs = new Vector3[(xSize +1) * (ySize + 1)];

1 Like