using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
public static class GameObjectExtension
{
///
/// 복제하여 서브매쉬 별로 게임오브젝트 만들기
///
/// 게임 오브젝트
/// 메쉬 콜라이더 사용여부
/// 만들어진 서브매쉬 게임오브젝트
public static GameObject[] CloneSubMeshAll(this GameObject go, bool meshCol)
{
MeshFilter meshFilter = go.GetComponent();
if (meshFilter == null) return null;
Mesh mesh = meshFilter.sharedMesh;
if (mesh == null) return null;
MeshRenderer meshRenderer = go.GetComponent();
int subMeshCount = mesh.subMeshCount;
GameObject[] gos = new GameObject[subMeshCount];
for (int i = 0; i < subMeshCount; i++)
{
GameObject newGo = new GameObject(string.Format("{0}_{1}", go.name, i));
newGo.transform.SetParent(go.transform.parent);
newGo.transform.localPosition = go.transform.localPosition;
newGo.transform.localEulerAngles = go.transform.localEulerAngles;
newGo.transform.localScale = go.transform.localScale;
MeshFilter mf = newGo.AddComponent();
mf.sharedMesh = mesh.CloneSubmesh(i);
mf.sharedMesh.name = string.Format("{0}_{1}", mesh.name, i);
Debug.Log(string.Format("{0}: {1}", mf.sharedMesh.name, mf.sharedMesh.vertices.Length));
MeshRenderer mr = newGo.AddComponent();
if (meshRenderer.sharedMaterials.Length > i)
{
mr.sharedMaterial = meshRenderer.sharedMaterials[i];
}
if (meshCol)
{
newGo.AddComponent();
}
gos[i] = newGo;
}
return gos;
}
///
/// Mesh Vertex 개수 가져오기
///
///
///
public static int GetVertexCount(this GameObject go)
{
if (go != null)
{
MeshFilter mf = go.GetComponent();
if (mf != null)
{
Mesh mesh = mf.sharedMesh;
if (mesh != null)
{
return mesh.vertexCount;
}
}
}
return 0;
}
public static int GetMeshCount(this GameObject go)
{
if (go != null)
{
MeshFilter mf = go.GetComponent();
if (mf != null)
{
Mesh mesh = mf.sharedMesh;
if (mesh != null)
{
return mesh.triangles.Length;
}
}
}
return 0;
}
///
/// 메트리얼 개수대로 게임오브젝트 분리하기
///
/// 게임오브젝트
/// MeshCollider 사용여부
/// split 과정에서 발생하는 Material 없는 오브젝트 삭제 여부
/// 분리된 오브젝트 배열
public static GameObject[] SplitSubMesh(this GameObject go, bool useCollider, bool removeNoMaterialObject)
{
GameObject[] objs = go.CloneSubMeshAll(useCollider);
if (removeNoMaterialObject)
{
if (objs != null)
{
for (int i = 0; i < objs.Length; i++)
{
MeshRenderer meshRenderer = objs[i].GetComponent();
if (meshRenderer.sharedMaterial == null)
{
GameObject.DestroyImmediate(objs[i]);
}
}
}
}
return objs;
}
}