Hello all,
I’m combining meshes into one big mesh. This works. However, each mesh has a different material. So I combined each material into one texture atlas. This works.
However, now I have a big mesh with a texture that represents the combined materials of the original meshes gameObjects.
How do I remap the UV of my combined mesh?
Here is my code for combining and texture atlas:
void CombineMeshes()
{
GameObject meshContainer = new GameObject("Level");
meshContainer.AddComponent<MeshFilter>();
meshContainer.AddComponent<MeshCollider>();
meshContainer.AddComponent<MeshRenderer>();
GameObject[] objectsInScene = FindObjectsByType<GameObject>(FindObjectsSortMode.None);
foreach (GameObject obj in objectsInScene)
{
if(obj.layer == 3 && obj.transform.parent != null && obj.tag != "Entity")
{
obj.transform.parent = meshContainer.transform;
}
}
//////////////////////////////make texture atlas///////////////////////////////
List<Texture2D> listOfTextures = new List<Texture2D> ();
int t = 0;
while(t < meshContainer.transform.childCount)
{
listOfTextures.Add(meshContainer.transform.GetChild(t).GetComponent<Renderer>().material.mainTexture as Texture2D);
t++;
}
Texture2D[] atlasTextures = listOfTextures.ToArray();
Texture2D atlas = new Texture2D(8192, 8192);
Rect[] rects = atlas.PackTextures(atlasTextures, 2, 8192);
print(rects.Length);
Material levelMaterial = new Material(meshContainer.transform.GetChild(0).GetComponent<Renderer>().material);
levelMaterial.mainTexture = atlas;
///////////////////////////////////////////////////////////////////////////////////
MeshFilter[] meshFilters = meshContainer.GetComponentsInChildren<MeshFilter>();
CombineInstance[] combine = new CombineInstance[meshFilters.Length];
int i = 1;
while (i < meshFilters.Length)
{
combine[i].mesh = meshFilters[i].sharedMesh;
combine[i].transform = meshFilters[i].transform.localToWorldMatrix;
meshFilters[i].gameObject.SetActive(false);
i++;
}
Mesh mesh = new Mesh();
mesh.indexFormat = UnityEngine.Rendering.IndexFormat.UInt32;
mesh.CombineMeshes(combine, true);
mesh.Optimize();
//mesh.RecalculateBounds();
meshContainer.transform.GetComponent<MeshFilter>().sharedMesh = mesh;
meshContainer.GetComponent<MeshCollider>().sharedMesh = mesh;
meshContainer.GetComponent<Renderer>().material = levelMaterial;
meshContainer.transform.gameObject.SetActive(true);
int m = 0;
while(m < meshContainer.transform.childCount)
{
Destroy(meshContainer.transform.GetChild(m).gameObject);
m++;
}
foreach(GameObject obj in objectsInScene)
{
if(obj.layer == 3 && obj.transform.parent == null && obj.tag != "Entity")
{
Destroy(obj.gameObject);
}
}
}
I’ve never really worked with meshes and uvs before, so this is new territory for me.






