유니티 메쉬를 추출하자!

 

Mesh Baker 에셋을 이용하여 모델을 추출해냈는데 문제가 생겼습니다.

 

유니티 MeshBaker

MeshBaker란? 여러 개의 메시를 하나의 큰 메시로 결합하고 해당 오브젝트의 텍스처를 텍스처 아틀라스 및 텍스처 배열로 만드는 데 있어 도움을 주는 툴(Tool)입니다. 텍스쳐 아틀라스를 사용하지

wlsdn629.tistory.com

메쉬..? / export할 때 메쉬가 없다 

 

뽑아낸 모델의 메쉬를 보니 할당은 되어 있는데 따로 리소스가 생겨나지 않았습니다.

리소스로 생겨나지 않았기 때문에 모델을 건내줄 때 메쉬가 없는채로 주게 되어, 모델을 받는 쪽에서는 아무것도 보이지 않는 문제가 생깁니다. (모델을 줄 때 export 했다는 과정)

 

그 외에도 해당 모델을 실수로 삭제한다고 하면 다시는 메시를 복구할 방법이 없다는 문제 등이 있습니다. 

 


해결 방법 

#if UNITY_EDITOR
using UnityEditor;
using UnityEngine;

public class ExtractMesh : MonoBehaviour
{
    private Mesh mesh;

    [ContextMenu("ExtractMesh")]
    private void ExtractMeshFrom3DModel()
    {
        var meshFilter = GetComponent<MeshFilter>();
        if (meshFilter == null)
        {
            Debug.LogError("MeshFilter component not found!");
            return;
        }

        mesh = meshFilter.sharedMesh; 
        if (mesh == null)
        {
            Debug.LogError("No mesh found in MeshFilter component!");
            return;
        }

        string path = $"Assets/Meshes/{gameObject.name}.asset";
        CreateDirectoryIfNotExists(path);
        
        if (AssetDatabase.LoadAssetAtPath<Mesh>(path) != null)
        {
            path = AssetDatabase.GenerateUniqueAssetPath(path);
        }

        AssetDatabase.CreateAsset(mesh, path);
        AssetDatabase.SaveAssets();
    }

    private void CreateDirectoryIfNotExists(string path)
    {
        string directoryPath = System.IO.Path.GetDirectoryName(path);
        if (!System.IO.Directory.Exists(directoryPath))
        {
            System.IO.Directory.CreateDirectory(directoryPath);
        }
    }
}
#endif

 

위 코드를 이용하여 ExtractMesh 스크립트를 만들어줍니다.

컴포넌트 부착

 

컴포넌트를 붙여준 다음, 컴포넌트를 우클릭하여 "Extract Mesh"를 눌러줍니다.

(좌) 성공했을 때 / (우) 실패했을 때

 

성공적으로 메쉬가 추출이 되면 왼쪽 사진처럼 Meshes폴더에 메쉬가 생겨나게 됩니다.

만약 이미 메쉬를 뽑아냈는데 또 추출하려고 시도하면 우측 사진처럼 에러 메세지가 나오면서 추출이 실패되게 됩니다.