I am trying to combine multiple textures into a texture atlas using Texture2D.PackTextures() which works fine. I create a new material for all the materials used on my mesh and sub-meshes. I end up with a new Packed Texture with 4 images.
This new material using the texture atlas is then applied to all my mesh and submeshes.
I then modify the UVs of my mesh and submeshes to point to the new image within the texture atlas. But what I seem to get is the complete texture atlas being used as the single texture, rather than the image within the atlas.
This is what I am expecting (apologies for the dark colours, there's no lights in my test scene!):
And this is what I get:
I've checked the UVs and they look to be getting updated correctly.
Any ideas as to what I'm missing?
This is my code snippet, its nothing fancy.
Material atlasMaterial = new Material(Shader.Find("Diffuse Fast"));
Component[] filters = GetComponentsInChildren(typeof(MeshFilter));
Texture2D[] textures = new Texture2D[filters.Length];
for (int i=0 ; i<filters.Length ; i++)
{
textures _= (Texture2D)filters*.gameObject.renderer.material.mainTexture;*_
_*}*_
_*textureAtlas=new Texture2D(maxSquareTextureSize,maxSquareTextureSize);*_
_*Rect[] uvs = textureAtlas.PackTextures(textures,0,maxSquareTextureSize);*_
_*atlasMaterial.mainTexture = textureAtlas;*_
_*Vector2[] oldUV,newUV;*_
_*for (int i=0 ; i<filters.Length ; i++)*_
_*{*_
<em>_filters*.gameObject.renderer.material=atlasMaterial;*_</em>
<em><em>_oldUV = (Vector2[])(((MeshFilter)filters*).mesh.uv);*_</em></em>
<em><em>_*newUV = new Vector2[oldUV.Length];*_</em></em>
<em><em>_*for (int j=0 ; j<oldUV.Length ; j++)*_</em></em>
<em><em>_*{*_</em></em>
<em><em><em><em>newUV[j]=new Vector2((oldUV[j].x*uvs_.width)+uvs*.x,*_</em></em></em></em>
<em><em><em><em><em><em>(oldUV[j].y*uvs_.height)+uvs*.y);*_</em></em></em></em></em></em>
<em><em><em><em><em><em>_*}*_</em></em></em></em></em></em>
<em><em><em><em><em><em><em>_((MeshFilter)filters*).mesh.uv=newUV;*_</em></em></em></em></em></em></em>
<em><em><em><em><em><em><em>_*}*_</em></em></em></em></em></em></em>
<em><em><em><em><em><em><em>_*```*_</em></em></em></em></em></em></em>