When I set the triangles inside the mesh generation function I have no problems everything works.
However when I try to put it in a separate function like this i get an error. In the below code I'm trying to put it in the Set() function. I need to be able to do this in separate functions. What am I doing wrong?
// mesh.SetTriangles(triangles, 0); // WORKS FINE JUST THIS
Set();
this.gameObject.GetComponent().sharedMesh = mesh;
return mesh;
}
public void Set()
{
mesh.SetTriangles(triangles, 0);
}
This is the error message i receive:
Failed setting triangles. Some indices are referencing out of bounds vertices. IndexCount: 194400, VertexCount: 0
UnityEngine.Mesh:SetTriangles(List`1, Int32)
GeneratedMesh:Set() (at Assets/Scripts/GeneratedMesh.cs:83)
GeneratedMesh:Generate() (at Assets/Scripts/GeneratedMesh.cs:73)
GeneratedMesh:Start() (at Assets/Scripts/GeneratedMesh.cs:19)
Here is the entire script.
public class GeneratedMesh : MonoBehaviour
{
public float size = 4;
public int gridSize = 16;
private MeshFilter filter;
public Mesh mesh { get { return filter.mesh; } }
// Start is called before the first frame update
void Start()
{
filter = GetComponent();
filter.mesh = Generate();
SendMessage("MeshRegernerated");
}
public List triangles = new List();
Mesh Generate()
{
Mesh mesh = new Mesh();
mesh.subMeshCount = 3;
var vertices = new List();
var normals = new List();
var uvs = new List();
for (int x = 0; x < gridSize + 1; x++)
{
for (int z = 0; z < gridSize + 1; z++)
{
float perY = Mathf.PerlinNoise(x * 0.02f,z * 0.02f ) * 2;
//create the verts
vertices.Add(new Vector3(-size * 0.5f + size * (x / ((float)gridSize)), perY, -size * 0.5f + size * (z / ((float)gridSize))));
//create the normals
normals.Add(Vector3.up);
uvs.Add(new Vector2(x / (float)gridSize, z / (float)gridSize));
}
}
//var triangles = new List();
var vertcount = gridSize + 1;
for (int i = 0; i < vertcount * vertcount - vertcount; i++)
{
if((i + 1) % vertcount == 0)
{
continue;
}
triangles.AddRange(new List()
{
i+ 1 + vertcount, i + vertcount,i,
i ,i +1 , i + vertcount + 1
});
}
//sets them all
mesh.SetVertices(vertices);
mesh.SetNormals(normals);
mesh.SetUVs(0,uvs);
// mesh.SetTriangles(triangles, 0);
Set();
this.gameObject.GetComponent().sharedMesh = mesh;
return mesh;
}
public void Set()
{
mesh.SetTriangles(triangles, 0);
}
}
↧