簡體   English   中英

從游戲對象UNITY C#創建網格

[英]Create a mesh from gameobjects UNITY C#

我的場景中產生了許多游戲對象。 有沒有一種方法可以創建一個網格來連接所有點,從而形成一個實體網格? 我已經研究了蒙皮網格物體,但是我不確定如何將其用於此目的。

謝謝。

我想與網格物體連接在一起的游戲對象

您可以使用Mesh.CombineMeshes函數從多個網格或Mesh.CombineMeshes創建一個網格。 首先,創建一個名為“ dots”的標簽,並確保這些對象具有此標簽,以使其更易於查找。 使用GameObject.FindGameObjectsWithTag通過標記查找所有點GameObject.FindGameObjectsWithTag 創建CombineInstance數組,並使用mesh初始化每個CombineInstance並從每個點transform MeshFilter信息。

創建新的GameObject來容納新的組合對象,然后將MeshFilterMeshRenderer附加到其上。 將材料應用到它。 最后,使用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);
}

用法

public Material mat;

void Start()
{
    CombineDotMeshes(mat);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM