Unity问题(1)——mesh法线反转

将模型导入Unity后,发现模型正反面颠倒了,百度后发现需要将模型mesh法线反转。

  1. 运行时利用模型自带的MeshFilter进行法线反转,关闭运行则恢复原样。
    代码如下(linepublic GameObject line,在Unity中将想要法线反转的模型拖入其中):
	Vector3[] normals = line.GetComponent<MeshFilter>().mesh.normals;
	for (int i = 0; i < normals.Length; i++)
	{
		normals[i] = -normals[i];
	    }
	    line.GetComponent<MeshFilter>().mesh.normals = normals;
	
	    int[] triangles = line.GetComponent<MeshFilter>().mesh.triangles;
	    for (int i = 0; i < triangles.Length; i += 3)
	    {
	        int t = triangles[i];
	        triangles[i] = triangles[i + 2];
	        triangles[i + 2] = t;
	    }
	    line.GetComponent<MeshFilter>().mesh.triangles = triangles;
	}

这种方式参考该博客

  1. 如果模型还添加了MeshCollider组件,则需要对该组件中的Mesh也进行法线反转。
    代码和上面相似,只是将mesh改为了sharedMesh:
	Vector3[] normals = line.GetComponent<MeshCollider>().sharedMesh.normals;
    for (int i = 0; i < normals.Length; i++)
    {
        normals[i] = -normals[i];
    }
    line.GetComponent<MeshCollider>().sharedMesh.normals = normals;

    int[] triangles = line.GetComponent<MeshCollider>().sharedMesh.triangles;
    for (int i = 0; i < triangles.Length; i += 3)
    {
        int t = triangles[i];
        triangles[i] = triangles[i + 2];
        triangles[i + 2] = t;
    }
    line.GetComponent<MeshCollider>().sharedMesh.triangles = triangles;

你可能感兴趣的:(#,Unity,unity)