- Home /
Generating single triangle meshes at run-time
I'm working on a project that needs to create single triangle meshes where each vertex value is determined at run time by the user. The instance of this triangle needs to maintain its world position as well as the three vertices (modifying this post creation will change affect the mesh) that form the mesh. Using tutorials I've come up with the code below.
The problem with this is that it begins to lag once I generate 2-3 instances of it. Does anybody know what's causing this slowdown? Also, as an alternative would it be possible to have a single triangle prefab and manipulate the individual vertices on the mesh without it affecting all other instances?
MeshFilter meshFilter = GetComponent<MeshFilter>();
if(meshFilter == null)
{
Debug.LogError("MeshFilter not found");
return;
}
Mesh mesh = meshFilter.sharedMesh;
if(mesh == null)
{
meshFilter.mesh = new Mesh();
mesh = meshFilter.sharedMesh;
}
mesh.Clear ();
mesh.vertices = new Vector3[]{a,b,c};
mesh.triangles = new int[]{0,1,2};
mesh.RecalculateNormals();
mesh.RecalculateBounds();
mesh.Optimize();
Answer by DaveA · Jul 18, 2013 at 05:06 PM
You can use a prefab, but in that case, use meshFilter.mesh rather than sharedMesh, as it will then operate on this instance's copy of the mesh.
Since it's just a triangle, you probably don't need to call Optimize.
Thanks a lot. Regarding the slow down I mentioned that only seems to occur when I'm running it in the IDE for some reason. When I built the project it was fine.
Your answer
![](https://koobas.hobune.stream/wayback/20220613110403im_/https://answers.unity.com/themes/thub/images/avi.jpg)