Mesh not Rendering after being edited in script

Hey Guys.

I’m currently trying to create Marching Squares in Unity. For that purpose, I want to edit a Plane as such, that it becomes triangular (at least in my example here, in the full code there are more shapes possible).

Here is the part of the script:

GameObject plane = GameObject.CreatePrimitive(PrimitiveType.Plane);
GameObject.Destroy(plane.GetComponent<MeshCollider>());

mesh = new Mesh();
plane.GetComponent<MeshFilter>().mesh = mesh;
plane.transform.SetParent(parent);

Vector3[] vertices = new Vector3[] { new Vector3(0, 0, 0), new Vector3(0.5f, 0, 0), new Vector3(0, 0, 0.5f) };
int[] triangles = new int[] { 0, 1, 2 };
Vector3[] normals = new Vector3[] { Vector3.down, Vector3.down, Vector3.down };
Vector2[] uv = new Vector2[] { new Vector2(0, 0), new Vector2(0.5f, 0), new Vector2(0, 0.5f) };

mesh.name = "Procedural Marching Squares";
                
mesh.Clear();
mesh.vertices = vertices;
mesh.normals = normals;
mesh.uv = uv;
mesh.triangles = triangles;

plane.GetComponent<Renderer>().material = groud_material;

Note: most of the not-defined variables are just global variables defined in the inspector

As soon as I run the code, a plane appears in the hierarchy but is not visible on the screen. I can select it and can see the orange outline, but it doesn’t correctly render as an Object. Also, no wire-mesh is visible.

I tried running an example for creating a cube I found online which worked flawlessly. I’m trying to find the mistake for about an hour now, but I can’t get it to work.

~Okaghana

Follow the flow of the code… It creates a Plane, then immediately overwrites the mesh it comes with, with a fresh triangle mesh.

The mesh it makes has 3 hard-wired verts, and winds one triangle out of those. It winds it so the triangle faces downward… go below and look up. (Left hand winding rule in Unity.)

If you wanna see other more … modern ways of creating geometry, there’s a bunch of examples in my MakeGeo package, available free here:

MakeGeo is presently hosted at these locations:

https://bitbucket.org/kurtdekker/makegeo

https://github.com/kurtdekker/makegeo

So I changed the direction of the triangle-indices now.

Question: The way I put the vertices into the array was like this:

triangles[0] = new Vector3(0, 0, 0);       //Top-Left
triangles[1] = new Vector3(0.5f, 0, 0);  //Top-Right
triangles[2] = new Vector3(0, 0, 0.5f);  //Bottom-Left

I had heard of the Clockwise-Rule before and would this consider being the correct direction. I swapped Index 1 and 2 because that is the way they did it in MakeGeo. But now I would say that these are ordered anti-clockwise and so I’m a little bit confused why this counts as Clockwise.

Besides that, everything is correct now

Many Thanks
~Okaghana

1 Like