Auto weld (or connect) vertices after merge

Hi there,

Trying out the runtime api, I’ve been successfully merging two cubes meshes together through script.
During that process is there any way to optimize duplicate vertices?
What would be the easiest way to clean them up?

Thanks

If memory serves, I believe merging already does collapse coincident vertices. However if it doesn’t you can use the weld vertices function to do this.

https://docs.unity3d.com/Packages/com.unity.probuilder@4.0/api/UnityEngine.ProBuilder.MeshOperations.VertexEditing.html?q=weld#UnityEngine_ProBuilder_MeshOperations_VertexEditing_WeldVertices_UnityEngine_ProBuilder_ProBuilderMesh_System_Collections_Generic_IEnumerable_System_Int32__System_Single_

Sorry, I forgot to mention that, I was using Combine

var list = new List<ProBuilderMesh> { meshA, meshB };
CombineMeshes.Combine(list, meshA);

which doesn’t seem to go through any collapsing of coincident vertices.

Maybe MergeElements is the way to go then…

I bump this question.
There seems no way to collapse coincident vertices automatically it seems or I wrongly interpreting docs and examples.

I just want to collapse all coincident vertices so only one vertex per world position would be left. Isin’t tehre any easy way to do it @kaarrrllll ?/

In the Editor ProBuilder handles this automatically through EditorMeshUtility.Optimize call. At runtime you will need to use MeshUtility.CollapseSharedVertices directly.

After hours of debugging, I found some answers to my problem.
The first mistake was that I assumed when merging/collapsing shared vertices will transform probuilder mesh vertices data. So there will be fewer vertices. Instead what is happening it does not change the vertices data but it does change the sharedvertices. So if I do

SharedVertex.GetSharedVerticesWithPositions(mesh.VerticesInWorldSpace())
     .Where(vert => vert.Count > 1)
     .ToList()
     .ForEach(vertex => mesh.MergeVertices(vertex.ToArray(), true));

    MeshUtility.CollapseSharedVertices(mesh.GetComponent<MeshFilter>().sharedMesh);

It will indeed merge the vertices into shared vertex but that vertex will contain all indexes of vertices being at the same position.

Not sure if the collapsesharedvertices there is needed? I think it would be needed if i moved the vertices itself??

int[] faces = mesh.faces.SelectMany(x => x.indexes).ToArray();
    mesh.WeldVertices(faces, Mathf.Epsilon);

I’m stupid and this actually works. But because of confusion that the vertices will be removed I though it doesn’t work…

Glad you got it working. Was the point of confusion that CollapseSharedVertices applies to the MeshFilter.sharedMesh rather than ProBuilderMesh component?