Advertisement
evelynshilosky

MeshMerger

Nov 19th, 2024
47
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.81 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEditor;
  4. using UnityEngine;
  5.  
  6. public class MeshMerger : MonoBehaviour
  7. {
  8.     public GameObject[] meshesToMerge;
  9.  
  10.     [ContextMenu("Merge Meshes")]
  11.     void MergeMeshes()
  12.     {
  13.         if (meshesToMerge.Length != 4)
  14.         {
  15.             Debug.LogError("Please assign exactly 5 meshes to merge.");
  16.             return;
  17.         }
  18.  
  19.         List<CombineInstance> combine = new List<CombineInstance>();
  20.         MeshFilter[] meshFilters = new MeshFilter[meshesToMerge.Length];
  21.  
  22.         for (int i = 0; i < meshesToMerge.Length; i++)
  23.         {
  24.             meshFilters[i] = meshesToMerge[i].GetComponent<MeshFilter>();
  25.             if (meshFilters[i] == null)
  26.             {
  27.                 Debug.LogError($"MeshFilter component not found on GameObject {i}");
  28.                 return;
  29.             }
  30.         }
  31.  
  32.         for (int i = 0; i < meshFilters.Length; i++)
  33.         {
  34.             CombineInstance ci = new CombineInstance();
  35.             ci.mesh = meshFilters[i].sharedMesh;
  36.             ci.transform = meshFilters[i].transform.localToWorldMatrix;
  37.             combine.Add(ci);
  38.         }
  39.  
  40.         Mesh combinedMesh = new Mesh();
  41.         combinedMesh.CombineMeshes(combine.ToArray());
  42.  
  43.         GameObject mergedObject = new GameObject("MergedMesh");
  44.         MeshFilter mergedMeshFilter = mergedObject.AddComponent<MeshFilter>();
  45.         mergedMeshFilter.sharedMesh = combinedMesh;
  46.  
  47.         MeshRenderer mergedMeshRenderer = mergedObject.AddComponent<MeshRenderer>();
  48.         mergedMeshRenderer.sharedMaterial = meshesToMerge[0].GetComponent<MeshRenderer>().sharedMaterial;
  49.  
  50.         // Save the combined mesh as an asset
  51.         AssetDatabase.CreateAsset(combinedMesh, "Assets/MergedMesh.asset");
  52.         AssetDatabase.SaveAssets();
  53.     }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement