- Home /
Unity won't show my programatically created Mesh(A Simple Triangle)
Hi, my question is simple. I'm trying to create a triangle. But it does not appear to the camera. What's missing? What am I doing wrong? I tried to create a .obj with the same vertices and it worked, why my mesh does not appear?
Here's the code:
GameObject.FindWithTag("Player").AddComponent();
Vector3[] verts = new Vector3[4]; Vector3[] normals = new Vector3[4]; Vector2[] uv = new Vector2[4]; int[] tri = new int[6];
//MeshFilter mf = GetComponent(MeshFilter);
verts[2] = new Vector3(0, 0, 0);
verts[1] = new Vector3(100, 0, 0);
verts[0] = new Vector3(0, 0, 100);
verts[3] = new Vector3(100, 0, 100);
for (int i = 0; i < normals.Length; i++) {
normals[i] = Vector3.up;
}
uv[0] = new Vector2(0, 0);
uv[1] = new Vector2(1, 0);
uv[2] = new Vector2(0, 1);
uv[3] = new Vector2(1, 1);
tri[0] = 0;
tri[1] = 2;
tri[2] = 3;
tri[3] = 0;
tri[4] = 3;
tri[5] = 1;
Mesh mesh = new Mesh();
mesh.vertices = verts;
mesh.triangles = tri;
mesh.uv = uv;
mesh.normals = normals;
Color[] color = new Color[4];
color[2] = new Color(1, 0, 0);
color[1] = new Color(0, 1, 0);
color[0] = new Color(0, 0, 1);
color[3] = new Color(0, 1, 0);
mesh.colors = color;
GameObject.FindWithTag("Player").GetComponent<MeshFilter>().mesh = mesh;
Answer by Andre 1 · Mar 12, 2011 at 07:02 AM
Oh, I found out, I missed adding the meshrenderer...
It would have been really helpful if you'd shown exactly what you did to fix it, too! As it is, we've got the non-working code, and only part of the knowledge that you've found a solution.
Answer by Madrayken · Dec 12, 2012 at 01:59 PM
To clarify:
If this code is added to a script's 'Start' method, which is then attached to a blank gameObject, you'll have to add both a MeshFilter and MeshRenderer component to the gameObject in order for the code to display anything. A pure, blank, empty game-object won't display any results at all.