简体   繁体   中英

Create a mesh from gameobjects UNITY C#

I have many gameobjects spawned in my scene. Is there a way to create a mesh to connect all the dots to make a solid mesh? I have researched skinned meshed but i am not sure how to use it for this purpose.

Thank you.

我想与网格物体连接在一起的游戏对象

You can create one mesh from multiple meshes or GameObjects with the Mesh.CombineMeshes function. First, create a tag named "dots" and make sure those objects have this tag to make them easier to find. Find all the dot GameObjects by tag with GameObject.FindGameObjectsWithTag . Create array of CombineInstance and initialize each CombineInstance with the mesh and transform information of MeshFilter from each dot.

Create new GameObject to hold the new combined Objects then attach MeshFilter and MeshRenderer to it. Apply a material to it. Finally, use MeshFilter.CombineMeshes to combine all those meshes stored in 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);
}

Usage :

public Material mat;

void Start()
{
    CombineDotMeshes(mat);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM