Mesh Manipulation - Mesh重置中心点

做项目的时候,偶尔会遇到美术提供的模型的中心点不统一,或者中心点设置的不符合程序的要求,以前为了解决这个问题,要么是找美术重新修改Mesh,要不然就是在模型外面再套一层壳,然后通过把模型放在壳下面,设置localPosition,然后通过操作壳来达到需求。但是这样做又会无故增加复杂度,也很容易出bug。
所以,为了一次性解决这类型的问题,就让程序充当一次美术吧

using UnityEngine;

namespace LDFW.Model
{

    public class MeshShifter : MonoBehaviour
    {

        public static Mesh targetMesh;
        public static Vector3 center;
        public static Vector3 offset;
        public static string savePath = "Assets/";


        public static Mesh SetMeshCenter(Mesh targetMesh, Vector3 targetReferenceCenter)
        {
            if (targetMesh == null)
            {
                Debug.LogError("Target mesh cannot be null!");
                return null;
            }

            //Debug.Log("Set mesh");
            Mesh newMesh = MeshGenerator.DuplicateMesh(targetMesh);
            
            
            Vector3 diff = Vector3.Scale(targetMesh.bounds.size * 0.5f, targetReferenceCenter * -1) - targetMesh.bounds.center;

            int vertexCount = targetMesh.vertexCount;
            Vector3[] oldVertices = newMesh.vertices;
            Vector3[] newVertices = new Vector3[vertexCount];

            for (int i = 0; i < vertexCount; i++)
            {
                newVertices[i] = oldVertices[i] + diff;
            }
            newMesh.vertices = newVertices;
            oldVertices = null;
            

            newMesh.RecalculateBounds();
            newMesh.RecalculateNormals();

            System.GC.Collect();
            return newMesh;
        }

        public static Mesh ShiftMesh(Mesh targetMesh, Vector3 offsetValue)
        {
            if (targetMesh == null)
            {
                Debug.LogError("Target mesh cannot be null!");
                return null;
            }

            Mesh newMesh = MeshGenerator.DuplicateMesh(targetMesh);


            Vector3 diff = offsetValue;

            int vertexCount = targetMesh.vertexCount;
            Vector3[] oldVertices = newMesh.vertices;
            Vector3[] newVertices = new Vector3[vertexCount];

            for (int i = 0; i < vertexCount; i++)
            {
                newVertices[i] = oldVertices[i] + diff;
            }
            newMesh.vertices = newVertices;
            oldVertices = null;


            newMesh.RecalculateBounds();
            newMesh.RecalculateNormals();

            System.GC.Collect();
            return newMesh;
        }
    }

}

返回的是Mesh类型,然后再写个保存方法,把Mesh以.asset格式保存到项目里

        #if UNITY_EDITOR
        public static void SaveAssetToFile(Object asset, string path, string extension = "asset")
        {
            AssetDatabase.CreateAsset(asset, path + "." + extension);
        }
        #endif

然后新的Mesh就可以替代原来的了,想怎么改都可以。

你可能感兴趣的:(Mesh Manipulation - Mesh重置中心点)