ggg.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. public class ggg : MonoBehaviour
  5. {
  6. // Start is called before the first frame update
  7. void Start()
  8. {
  9. CombineMesh();
  10. }
  11. // Update is called once per frame
  12. void Update()
  13. {
  14. }
  15. void CombineMesh()
  16. {
  17. //获取所有子物体的网格
  18. MeshFilter[] mfChildren = GetComponentsInChildren<MeshFilter>();
  19. CombineInstance[] combine = new CombineInstance[mfChildren.Length];
  20. //获取所有子物体的渲染器和材质
  21. MeshRenderer[] mrChildren = GetComponentsInChildren<MeshRenderer>();
  22. Material[] materials = new Material[mrChildren.Length];
  23. //生成新的渲染器和网格组件
  24. MeshRenderer mrSelf = gameObject.AddComponent<MeshRenderer>();
  25. MeshFilter mfSelf = gameObject.AddComponent<MeshFilter>();
  26. //合并子纹理
  27. Texture2D[] textures = new Texture2D[mrChildren.Length];
  28. Debug.Log(mrChildren.Length+"xxxxxxxxxxxxxxxxxxxxx");
  29. for (int i = 0; i < mrChildren.Length; i++)
  30. {
  31. if (mrChildren[i].transform == transform)
  32. {
  33. continue;
  34. }
  35. materials[i] = mrChildren[i].sharedMaterial;
  36. Texture2D tx = materials[i].GetTexture("_MainTex") as Texture2D;
  37. Texture2D tx2D = new Texture2D(tx.width, tx.height, TextureFormat.ARGB32, false);
  38. tx2D.SetPixels(tx.GetPixels(0, 0, tx.width, tx.height));
  39. tx2D.Apply();
  40. textures[i] = tx2D;
  41. }
  42. //生成新的材质
  43. Material materialNew = new Material(materials[0].shader);
  44. materialNew.CopyPropertiesFromMaterial(materials[0]);
  45. mrSelf.sharedMaterial = materialNew;
  46. //设置新材质的主纹理
  47. Texture2D texture = new Texture2D(1024, 1024);
  48. materialNew.SetTexture("_MainTex", texture);
  49. Rect[] rects = texture.PackTextures(textures, 10, 1024);
  50. //根据纹理合并的信息刷新子网格UV
  51. for (int i = 0; i < mfChildren.Length; i++)
  52. {
  53. if (mfChildren[i].transform == transform)
  54. {
  55. continue;
  56. }
  57. Rect rect = rects[i];
  58. Mesh meshCombine = mfChildren[i].mesh;
  59. Vector2[] uvs = new Vector2[meshCombine.uv.Length];
  60. //把网格的uv根据贴图的rect刷一遍  
  61. for (int j = 0; j < uvs.Length; j++)
  62. {
  63. uvs[j].x = rect.x + meshCombine.uv[j].x * rect.width;
  64. uvs[j].y = rect.y + meshCombine.uv[j].y * rect.height;
  65. }
  66. meshCombine.uv = uvs;
  67. combine[i].mesh = meshCombine;
  68. combine[i].transform = mfChildren[i].transform.localToWorldMatrix;
  69. mfChildren[i].gameObject.SetActive(false);
  70. }
  71. //生成新的网格,赋值给新的网格渲染组件
  72. Mesh newMesh = new Mesh();
  73. newMesh.CombineMeshes(combine, true, true);//合并网格  
  74.         mfSelf.mesh = newMesh;
  75. }