Display a simple mesh (2D square) on the screen?

Hi,

For a test I’m trying to just display a simple mesh (2D square) on the screen.

I created an empty gameobject with just a MeshFilter component and a Script component. Here’s the simple code in UnityScript. There’s no errors, but it doesn’t show anything on the screen.

function Start () {
    // Create the vertices
	var Vertices = Array();
	Vertices[0] = Vector3(0, 0, 0);
	Vertices[1] = Vector3(1, 0, 0);
	Vertices[2] = Vector3(0, 1, 0);
	Vertices[3] = Vector3(1, 1, 1);

    // Create the UVs
	var UVs = Array();
	UVs[0] = Vector2(0, 1);
	UVs[1] = Vector2(1, 1);
	UVs[2] = Vector2(0, 0);
	UVs[3] = Vector2(1, 0);

    // Create the 2 triangles
	var triangles = [ 0, 1, 3, 3, 2, 0 ];

    // Display the mesh
	var m = Mesh();
	GetComponent.<MeshFilter>().mesh = m;
	m.vertices = Vertices;
	m.uv = UVs;
	m.triangles = triangles;
}

Can you see where’s my mistake? Thanks!

I use C# not JS so you’re going to have to search some of this on your own but I can see a few mistakes. First you actually need to create a new gameobject to create the mesh on.

var square: GameObject;
square= new GameObject ("Square");

You then need to use AddComponent to create a MeshRenderer and a MeshFilter or nothing is going to render.

I’m not sure why var m = Mesh(); isn’t resulting in an error, perhaps in JS it doesn’t but if you check the documentation you’ll see what you should be using.

Also your vertices do not describe a square. A two dimensional shape is always going to have one axis that is all the same but you are modifying all three, hence creating a three dimensional shape. Your vertices describe a square folded over on itself with dodgy normals.

 Vertices[0] = Vector3(-1, 0, -1);
 Vertices[1] = Vector3(-1, 0, 1);
 Vertices[2] = Vector3(1, 0, 1);
 Vertices[3] = Vector3(1, 0, -1);

That is for a square. Whichever axis you want it to be drawn on should all be the same, ie 0.

Your triangles are also wrong.

 var triangles = [ 0, 1, 2, 0, 2, 3 ];

Those are the values you want to go with the above vertices.

Which makes the UV co-ordinates:

     UVs[0] = Vector2(0, 0);
     UVs[1] = Vector2(0, 1);
     UVs[2] = Vector2(1, 1);
     UVs[3] = Vector2(1, 0);

It may then be necessary to use RecalculateNormals for it to display correctly.

You may also want to declare the values of m.vertices and m.uv directly rather than in a separate array.