Problem with Procedural Mesh Generation
Hi All,
I am currently having an issue with mesh generation, I followed brackeys tutorial on Mesh Generation for procedural maps and seem to be having an issue that I cannot solve.
The problem I am having is, it isn't generating a grid with Perlin noise. It is instead generating what is being shown in the image below. It is just meant to be a grid like mesh.
Here is an image:
Image 2:
Here is my code:
using UnityEngine;
public class MeshGenerator : MonoBehaviour
{
public int xSize = 20;
public int zSize = 20;
Mesh mesh;
Vector3[] vertices;
int[] triangles;
void Start()
{
mesh = new Mesh();
GetComponent<MeshFilter>().mesh = mesh;
CreateShape();
UpdateMesh();
}
private void CreateShape()
{
vertices = new Vector3[(xSize + 1) * (zSize + 1)];
for (int i = 0, z = 0; z <= zSize; i++, z++)
{
for (int x = 0; x <= xSize; x++)
{
var y = Mathf.PerlinNoise(x * .3f, z * .3f) * 2f;
vertices[i] = new Vector3(x, y, z);
}
}
triangles = new int[xSize * zSize * 6];
var vert = 0;
var tris = 0;
for (var z = 0; z < zSize; z++)
{
for (var x = 0; x < xSize; x++)
{
triangles[vert + 0] = vert + 0;
triangles[vert + 1] = vert + xSize + 1;
triangles[vert + 2] = vert + 1;
triangles[vert + 3] = vert + 1;
triangles[vert + 4] = vert + xSize + 1;
triangles[vert + 5] = vert + xSize + 2;
vert++;
tris += 6;
}
vert++;
}
}
private void UpdateMesh()
{
mesh.Clear();
mesh.vertices = vertices;
mesh.triangles = triangles;
mesh.RecalculateNormals();
}
}
Regards,
Migo
@WSF$$anonymous$$igo, you don't describe what the problem is. You should edit your post to include that! And please be more specific than "it doesn't work."
Answer by streeetwalker · Mar 22, 2020 at 02:38 PM
You have two problems:
Your not incrementing i to match the full number of vertices your creating in the vertex generation loops - you increment i in the outer loop. But you should increase the value of I for every vertex you create, not for each row. So increment i in the inner loop, not as part of the loop declaration.
you need to increase the triangle array index by 'tris' not 'vert' (should be triangles[tris+ 0] and so on)
Cheers the i++ solved it and Ill change the tris now, in the comments of the youtube someone wrote that as a 'clean up' and forgot I did it!
EDIT: The tris worked too, thank you!