Workaround to Cloth Not Working After SetActive, Plus Undesired Collision

I have a sailing ship with beautifully detailed cloth sails that are toggled between raised/lowered positions via SetActive().

Unfortunately, in Unity 2017.3, they are also now (undesirably) collidable, which sucks for performance at VR framerates any time something touches one.

I spent several hours looking for a workaround. No settings changes would disable collisions. The collision ignores the physics layer matrix, and continues to collide after disabling both the Cloth and SkinnedMeshRenderer. (Disabling the gameObject itself works.)

I did eventually find a solution that I thought worth sharing here. Turns out, Unity is creating a hidden MeshCollider for EVERY SINGLE VERTEX in the cloth, regardless of how you tweak your cloth settings.

So, in addition to the tweak of toggling cloth off/on every time it is reactivated, you now have to remove every single attached MeshCollider (there may be hundreds!) if you don’t want collisions.

Here’s a script that solves both problems:

using UnityEngine;

public class ClothFix : MonoBehaviour {

    Cloth cloth;

    void Awake() {
        cloth = GetComponent<Cloth>();
    }

    void OnEnable() {
        // workaround for SetActive not restarting cloth simulation
        cloth.enabled = false;
        cloth.enabled = true;
        // workaround for Unity 2017.3 adding a mesh collider to every single vertex regardless of settings
        foreach (MeshCollider c in GetComponents<MeshCollider>())
            Destroy(c);
    }

    void OnDisable() {
        cloth.enabled = false;
    }
}

Note: The MeshCollider removal can probably be moved to Awake(), but I’m superstitious at this point. Also, whoever implemented this crappy solution at Unity owes us all an apology!

3395277–267080–ClothFix.cs (588 Bytes)

1 Like

This bug set me back a few days on a project as well. Thank you for this! Works perfectly.

I have also noticed the meshcollider being added when I press apply button for the prefab with cloth. This happens for every apply button pressed, so if I have pressed 4 times, there would be 4 mesh collider components! Just in my case the mesh collider components were not hidden!

This has to be BUG.! It’s been like this for some time I think for 2017.3.