I programmatically create a Mesh and want to generate a texture that patches coloured squares together so that the patchwork perfectly matches the vertices.
The mesh's dimensions are expressed in floats, the texture dimensions are expressed in pixels.

myMeshFilter.mesh = BuildMesh();
// todo: how to find out the values instead of ??
myMeshRenderer.sharedMaterials[0].mainTexture = BuildTexture(??, ??);

private Texture BuildTexture(int width, int height){
    var texture = new Texture2D(width, height);
    var pixels = textures[TileType.Grass.Value]; //array of 64*64 pixels
    var tileWidth = width/NumberOfColumns;
    var tileHeight = height/NumberOfRows;

    //todo: do this for all the tiles instead of only the first;
    texture.SetPixels(0,0, tileWidth , tileHeight, pixels);

In the editor, you can set the pixel-to-unit ratio, but not sure how to set this on generated textures.

My current implementation assumed that setting and using my source texture's pixel to unit ratio in my calculations would do the trick, but I noticed that it doesn't and I Googled far and wide and have mostly become more confused with every hit.

I think I need the camera to translate my mesh's corner values to pixels, but not sure and wouldn't know how.

Pointing the UV's of the mesh to the correct points in the texture would be a solution (and probably a rather performant one), but would restrict me in my possibilities if I want the tiles to have visual-only 'overflows'.
eg: grass tile next to dirt tile would have a bit of grass over the dirt.


1 Answer 1


What you need to do is programmatically unwrap the UV map of the mesh to fit your texture, or, if you want to generate the texture as well, then use the UV vector array to create the texture. You do this by creating a Vector2 array and set the UV vectors respectively to it's vertices. Check this link for an example.

After setting up the UV map it's really just filling in the polygons given by the 2d vertices with the given texture or color.

  • \$\begingroup\$ If I'm understanding correctly you're suggesting to map the UV's to the correct point on the original texture, right? That could indeed be a solution for now. I added a bit more context to the OP to explain why I was hoping for another solution though. \$\endgroup\$ Commented Feb 10, 2014 at 14:16
  • 1
    \$\begingroup\$ If you want the "overflows", you should include these on your texture as well, and map the UV in a way that if the overflow is needed, the correct edges are at the seam. \$\endgroup\$
    – Kanadaj
    Commented Feb 10, 2014 at 15:47

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .