-
-
Save tsubaki/03ef8e6131e30bc91d49 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using System.Collections; | |
using System.Collections.Generic; | |
#if UNITY_EDITOR | |
using UnityEditor; | |
#endif | |
[ExecuteInEditMode] | |
public class MeshCombiner : MonoBehaviour { | |
#if UNITY_EDITOR | |
public GameObject generatedObject = null; | |
[ContextMenu("Export")] | |
void Init () | |
{ | |
Component[] meshFilters = GetComponentsInChildren<MeshFilter>(true); | |
Dictionary<Material, List<CombineInstance>> combineMeshInstanceDictionary = new Dictionary<Material, List<CombineInstance>> (); | |
foreach (var mesh in meshFilters) { | |
var mat = mesh.renderer.sharedMaterial ; | |
if( mat == null ) | |
continue; | |
if(!combineMeshInstanceDictionary.ContainsKey(mat) ) | |
{ | |
combineMeshInstanceDictionary.Add( mat, new List<CombineInstance>()); | |
} | |
var instance = combineMeshInstanceDictionary[ mat ]; | |
var cmesh = new CombineInstance(); | |
cmesh.transform = mesh.transform.localToWorldMatrix; | |
cmesh.mesh = ((MeshFilter) mesh).sharedMesh; | |
instance.Add(cmesh); | |
} | |
gameObject.SetActive (false); | |
gameObject.tag = "EditorOnly"; | |
if( generatedObject == null) | |
generatedObject = new GameObject (name); | |
foreach (var item in generatedObject.GetComponentsInChildren<Transform>()) { | |
if( item == generatedObject.transform ) | |
continue; | |
DestroyImmediate (item.gameObject); | |
} | |
generatedObject.isStatic = true; | |
foreach (var dic in combineMeshInstanceDictionary) { | |
var newObject = new GameObject(dic.Key.name); | |
newObject.isStatic = true; | |
var meshrenderer = newObject.AddComponent<MeshRenderer>(); | |
var meshfilter = newObject.AddComponent<MeshFilter>(); | |
meshrenderer.material = dic.Key; | |
var mesh = new Mesh(); | |
mesh.CombineMeshes(dic.Value.ToArray()); | |
Unwrapping.GenerateSecondaryUVSet( mesh); | |
meshfilter.sharedMesh = mesh; | |
newObject.transform.parent = generatedObject.transform; | |
Debug.Log(Application.loadedLevelName); | |
System.IO.Directory.CreateDirectory( "Assets/" + Application.loadedLevelName + "/" + name ); | |
AssetDatabase.CreateAsset(mesh, "Assets/" + Application.loadedLevelName+ "/" + name + "/" + dic.Key.name + ".asset"); | |
} | |
} | |
void OnEnable() | |
{ | |
if (generatedObject != null) { | |
generatedObject.SetActive(false); | |
} | |
} | |
void OnDisable() | |
{ | |
if (generatedObject != null) { | |
generatedObject.SetActive(true); | |
} | |
} | |
#endif | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment