How to combine materials at runtime?

Hi! I’ve been having a lot of fun making a tile generation system for my game, and for the most part it’s worked out pretty well. That is until I got to getting materials mapped. At this point I now have all the meshes merged, and all the materials synched onto it as well. BUT! They’re all separate on the newly formed mesh. They are all of the same texture, but at different offsets on that texture. In the name of my draw calls, please, someone suggest a solution, or point to a document I didn’t read and make me feel stupid. x) thanks.

You can’t “merge” materials. You just have to use the same material. You can’t use the materials offset / scale property to select the tile since that changes the texture matrix of that material. If all tiles should use the same material you don’t want to modify the scale / offset at all.

What you actually have to do is map the texture the “normal” way by changing the uv coordinates of your tiles. So instead of using

(0, 0)
(0, 1)
(1, 0)
(1, 1)

you would change the uvs of a tile to match it’s part on the texture. For example on a 4x4 texture atlas you might have something like

(0.25, 0.5 )
(0.25, 0.75)
(0.5,  0.5 )
(0.5,  0.75)

To calculate the uvs you just need to do something like this:

// C#
float u = 1.0f / xTiling;
float v = 1.0f / yTiling;

uv[0] = new Vector2(u*xTileIndex   , v*yTileIndex    ); // 0,0
uv[1] = new Vector2(u*xTileIndex   , v*yTileIndex +v ); // 0,1
uv[2] = new Vector2(u*xTileIndex +u, v*yTileIndex    ); // 1,0
uv[3] = new Vector2(u*xTileIndex +u, v*yTileIndex +v ); // 1,1

Of course it depends on how your tile-mesh actually looks like and where the vertices are, so you might need to swap some uvs to match your mesh. This you need to calculate for each tile.