Building a mesh...

How can I build a mesh script with more than a single triangle?

// Builds a mesh containing a single triangle with uv’s.
function Start ()
{
gameObject.AddComponent(“MeshFilter”);
gameObject.AddComponent(“MeshRenderer”);
var mesh : Mesh = GetComponent(MeshFilter).mesh;

mesh.Clear();
mesh.vertices = [Vector3(0,0,0), Vector3(0,1,0), Vector3(1, 1, 0)];
mesh.uv = [Vector2 (0, 0), Vector2 (0, 1), Vector2 (1, 1)];
mesh.triangles = [0, 1, 2];
}

I’ve tried writing a cube mesh generator without much luck. Someone who’s good at it should whip up a tutorial or a more complex code example.

I’d suggest looking at the mesh combine utility for example code of how to build stuff with the mesh interface. Once you understand that it’s just a matter of where you get the data to build the meshes. (Copied from existing models, read in from a data file, created programatically…)

–Eric

Thanks! But I cant get the generated triangles to connect with the Combine-script… Is there not a way to code a quad, or 2 triangles in one script ?

Also, the triangle mesh created will not be affected by the lights… why is that? textures are dark, but showing though.

Tore

A quad is basically two triangles (and usually four vertices if the quad is planar).

So if you have vertices laid out like this:

0---1
|  /|
| / |
|/  |
2---3

Then two triangles are [0, 1, 2] and [1, 3, 2] (or the other, i.e. anticlockwise way of going around the triangle… I never remember which one is the correct :)).

As for the lighting: computing lighting needs vertex normals, as well as positions, to be set. So at each vertex you need to supply a vector that “points outwards” the surface. Also note that for bump-mapping to work you also need to supply “tangent” vectors.

Thanks for good tips! :slight_smile:

Tore

I tried using CombineChildren script in unity which in turn uses MeshCombineUtilty to combine the MeshInstance, but how do I retrieve the game object of the combined mesh? as in, how do I get the Mesh object?

because when I look into the CombineChildren script, it creates a game object and parent it to the game object in which the script is attached, but I dont know how to get the mesh object from there, I only know how to get the transform child… Please kindly advice, thanks.

GameObject anObject = new GameObject("An Object");
anObject.AddComponent("CombineChildren");

Block b1 = (Block)Instantiate(prefab, position, rotation);
Block b2 = (Block)Instantiate(prefab, position2, rotation);

// attach to parent
b1.transform.parent = anObject.transform;
b2.transform.parent = anObject.transform;

// get the combined mesh..
...

GetComponent(MeshFilter). Look in the docs under Mesh for examples.

–Eric

what is mesh uv exactly? and how do I generate the uvs given the vertices and triangles of the mesh? the unity documentation about mesh’s uv doesnt really help me, please advice, thanks.

Oh… sorry, I just realized that I dont need to assign the uv to make a cube geometry…