Search Unity

Workaround to Cloth Not Working After SetActive, Plus Undesired Collision

Discussion in 'Physics' started by kideternal, Feb 18, 2018.

  1. kideternal

    kideternal

    Joined:
    Nov 20, 2014
    Posts:
    82
    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:
    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public class ClothFix : MonoBehaviour {
    4.  
    5.     Cloth cloth;
    6.  
    7.     void Awake() {
    8.         cloth = GetComponent<Cloth>();
    9.     }
    10.  
    11.     void OnEnable() {
    12.         // workaround for SetActive not restarting cloth simulation
    13.         cloth.enabled = false;
    14.         cloth.enabled = true;
    15.         // workaround for Unity 2017.3 adding a mesh collider to every single vertex regardless of settings
    16.         foreach (MeshCollider c in GetComponents<MeshCollider>())
    17.             Destroy(c);
    18.     }
    19.  
    20.     void OnDisable() {
    21.         cloth.enabled = false;
    22.     }
    23. }
    24.  
    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!
     

    Attached Files:

    Last edited: Feb 18, 2018
    Lukebox likes this.
  2. Guillermogrw

    Guillermogrw

    Joined:
    Nov 16, 2017
    Posts:
    4
    This bug set me back a few days on a project as well. Thank you for this! Works perfectly.
     
  3. castor76

    castor76

    Joined:
    Dec 5, 2011
    Posts:
    2,517
    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.