How to remove parts of a mesh durring runtime?

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

public class ShipCore : MonoBehaviour {

    public GameObject shipCore;

    void Start () {
        UpdateMesh ();
    }

    void Update () {
        if (Input.GetKeyDown(KeyCode.P)) {
            foreach (Transform t in shipCore.transform) {
                t.gameObject.SetActive (true);
                if (t.gameObject.name == "ship child cube 1") {
                    Destroy (t.gameObject);
                }
            }
            UpdateMesh ();
        }
    }

    void UpdateMesh () {
      
        MeshCollider col = shipCore.GetComponent<MeshCollider> ();
        if (col != null) {
            Destroy (col);
        }
        MeshFilter[] meshFilters = shipCore.GetComponentsInChildren<MeshFilter> ();
        CombineInstance[] combine = new CombineInstance[meshFilters.Length];
        int i = 0;
        while (i < meshFilters.Length) {
            combine [i].mesh = meshFilters [i].sharedMesh;
            combine [i].transform = meshFilters [i].transform.localToWorldMatrix;
            meshFilters [i].gameObject.SetActive (false);
            i++;
        }

        shipCore.GetComponent<MeshFilter>().mesh = new Mesh ();
        shipCore.GetComponent<MeshFilter> ().mesh.CombineMeshes(combine);
        shipCore.gameObject.SetActive (true);

        MeshCollider newCollider = shipCore.AddComponent<MeshCollider> ();


    }

}

Above is the code to my ship’s core. The core has three cubes attatched to it as childern objects. When the scene starts the ship core combines its mesh with the meshes of the child cubes and forms one solid mesh. Is there a way to make one of the cubes be removed from the mesh durring runtime? I want to make it look like part of the main mesh was removed when I press the “P” key.

Idea #1 - Don’t combine the meshes.
Idea #2 - Combine the mesh, but have a duplicate hidden object. Break the mesh when part of it required to be destroyed, recreate the mesh again, but without that part.

1 Like