从游戏对象UNITY C#创建网格

时间:2018-07-17 07:28:14

标签: c# unity3d

我的场景中产生了许多游戏对象。有没有一种方法可以创建一个网格来连接所有点,从而形成一个实体网格?我已经研究了蒙皮网格物体,但是我不确定如何将其用于此目的。

谢谢。

Gameobjects I want to connect together with mesh

1 个答案:

答案 0 :(得分:3)

您可以使用Mesh.CombineMeshes函数从多个网格或GameObject中创建一个网格。首先,创建一个名为“ dots” 的标签,并确保这些对象具有此标签,以使其更易于查找。用GameObject.FindGameObjectsWithTag通过标记查找所有点GameObjects。创建CombineInstance的数组,并使用每个点中CombineInstance的{​​{1}}和mesh信息来初始化每个transform

创建新的GameObject来容纳新的组合对象,然后将MeshFilterMeshFilter附加到其上。将材料应用到它。最后,使用MeshRenderer合并存储在MeshFilter.CombineMeshes中的所有那些网格。

CombineInstance

用法

void CombineDotMeshes(Material mat)
{
    //Find all the dots GameObjects
    GameObject[] allDots = GameObject.FindGameObjectsWithTag("dots");

    //Create CombineInstance from the amount of dots
    CombineInstance[] cInstance = new CombineInstance[allDots.Length];

    //Initialize CombineInstance from MeshFilter of each dot
    for (int i = 0; i < allDots.Length; i++)
    {
        //Get current Mesh Filter and initialize each CombineInstance 
        MeshFilter cFilter = allDots[i].GetComponent<MeshFilter>();

        //Get each Mesh and position
        cInstance[i].mesh = cFilter.sharedMesh;
        cInstance[i].transform = cFilter.transform.localToWorldMatrix;
        //Hide each MeshFilter or Destroy the GameObject 
        cFilter.gameObject.SetActive(false);
    }

    //Create new GameObject that will contain the new combined Mesh
    GameObject combinedMesh = new GameObject("CombinedDots");
    MeshRenderer mr = combinedMesh.AddComponent<MeshRenderer>();
    mr.material = mat;
    MeshFilter mf = combinedMesh.AddComponent<MeshFilter>();

    //Create new Mesh then combine it
    mf.mesh = new Mesh();
    mf.mesh.CombineMeshes(cInstance);
}