MeshCollider双面化脚本

由于MeshCollider组件可以挂载多个,所以不需要Mesh重新合并了。

除了反转法线还需要反转所有三角面的顺序

 

脚本如下:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DoubleSideMeshCollider : MonoBehaviour
{
    public MeshCollider meshCollider;


    void Start()
    {
        var mesh1 = meshCollider.sharedMesh;
        var mesh2 = Instantiate(mesh1);

        var normals = mesh2.normals;
        for (int i = 0; i < normals.Length; ++i)
        {
            normals[i] = -normals[i];
        }
        mesh2.normals = normals;

        for (int i = 0; i < mesh2.subMeshCount; ++i)
        {
            int[] triangles = mesh2.GetTriangles(i);
            for (int j = 0; j < triangles.Length; j += 3)
            {
                int temp = triangles[j];
                triangles[j] = triangles[j + 1];
                triangles[j + 1] = temp;
            }
            mesh2.SetTriangles(triangles, i);
        }

        gameObject.AddComponent<MeshCollider>().sharedMesh = mesh2;
    }
}

 

posted @ 2017-03-27 21:16  HONT  阅读(1908)  评论(0编辑  收藏  举报