How do you delete parts of a mesh within a certain color threshold based on texture and re-assemble the mesh afterwards? Below it seems I get back a bunch of messy triangles instead of just the vertices I want deleted

using UnityEngine;
using System.Collections.Generic;
using System.Linq;

public class MeshModifier : MonoBehaviour
    public Color thresholdColor = Color.white;
    public float colorThreshold = 0.1f;

    void Start()
        MeshFilter meshFilter = GetComponent<MeshFilter>();

        if (meshFilter != null)
            Mesh mesh = meshFilter.mesh;

    void DeleteVerticesByTextureCoordinate(Mesh mesh)
        Vector2[] textureCoordinates = mesh.uv;

        // Get the material assigned to the mesh renderer
        Material material = GetComponent<Renderer>().material;

        // Get the main texture from the material
        Texture2D texture = (Texture2D)material.mainTexture;

        // Create a list to store the valid vertices
        List<Vector3> validVertices = new List<Vector3>();
        List<int> validTriangles = new List<int>();

        // Iterate through vertices and delete based on texture coordinate color
        for (int i = 0; i < textureCoordinates.Length; i++)
            // Get the color from the texture at the current UV coordinate
            Color textureColor = texture.GetPixelBilinear(textureCoordinates[i].x, textureCoordinates[i].y);

            // Check if the color is within the threshold
            if (Vector4.Distance(textureColor, thresholdColor) >= colorThreshold)
                // Add the valid vertex to the list

                // Add the index of the valid vertex to the triangles array
                validTriangles.Add(validVertices.Count - 1);

                // If three vertices are collected, create a new triangle
                if (validTriangles.Count % 3 == 0)
                    mesh.triangles = validTriangles.ToArray();

        // Update the mesh with the valid vertices and triangles
        mesh.vertices = validVertices.ToArray();

        // Recalculate the normals

  • \$\begingroup\$ Do you really need to remove the vertices from the mesh, or would it suffice to use a shader that rejects the vertices just before rendering, or aborts individual fragments within that colour range to allow for shaped cut-outs? The more you can tell us about the game feature this is supporting, the better we can suggest suitable ways to implement it. \$\endgroup\$
    – DMGregory
    Commented Feb 10 at 12:54


You must log in to answer this question.

Browse other questions tagged .