Unity meshes

Playing around with Unity and trying to generate a Mesh. But if it is not known in advance how large the vertex and triangle lists have to be, ArrayLists are a solution, which apparantly cannot just be cast into a mesh.

Instinctively one would do
mesh.vertices = new Vector3[vtxarray.Count]
vtxarray.CopyTo(mesh.vertices)
but this copies the data and does not display the Mesh.
Instead it has to be assigned to another Vector3[] variable, then this variable can be assigned to mesh.vertices; I tested assigning mesh.vertices to itself after copying but that also didn’t work.

Here’s a working Quad example:

using UnityEngine;
using System.Collections;


public class Quad : MonoBehaviour {
	void Start () {
		//add a mesh and meshrenderer to this transform
		gameObject.AddComponent();
		Mesh mesh = gameObject.AddComponent().mesh;
		
		ArrayList verts = new ArrayList();
		ArrayList uvs = new ArrayList();
		ArrayList tris = new ArrayList();

		//generate the meshdata
		verts.Add( new Vector3(-1, 0, -1) );
		verts.Add( new Vector3(1, 0, -1) );
		verts.Add( new Vector3(-1, 0, 1) );
		verts.Add( new Vector3(1, 0, 1) );
		uvs.Add( new Vector2(0, 0) );
		uvs.Add( new Vector2(1, 0) );
		uvs.Add( new Vector2(0, 1) );
		uvs.Add( new Vector2(1, 1) );
		tris.Add(0);
		tris.Add(1);
		tris.Add(2);
		tris.Add(2);
		tris.Add(1);
		tris.Add(3);
		
		// copy arraylists to arrays, then apply arrays to mesh
		// it's impossible to use CopyTo(mesh.variable) directly
		// although printing the data gives valid output, mesh
		// is invisible
		Vector3[] vertices = new Vector3[verts.Count];
		verts.CopyTo(vertices);
		mesh.vertices = vertices;
		Vector2[] uv = new Vector2[uvs.Count];
		uvs.CopyTo(uv);
		mesh.uv = uv;
		int[] triangles = new int[tris.Count];
		tris.CopyTo(triangles);
		mesh.triangles = triangles;
		
		mesh.RecalculateNormals();
		mesh.RecalculateBounds();
	}
	

	void Update () {
	
	}
}

Leave a Reply

Your email address will not be published. Required fields are marked *