Search Unity

Assigning MeshCollider.sharedMesh causes performance spike in Mesh.Bake in physics

Discussion in 'Physics' started by tomas-maly, Sep 4, 2019.

  1. tomas-maly

    tomas-maly

    Joined:
    Mar 26, 2019
    Posts:
    1
    Hi,

    I have a zombie that has several body parts all rendered with SkinnedMeshRenderer. When I hit the zombie, I want it to break up into individual parts. I iterate over the parts, remove SkinnedMeshRenderer and add RigidBody, MeshCollider and MeshRenderer.

    The problem is that assigning the sharedMesh of the MeshCollider causes lag spike. The lag spike is in Mesh.Bake in physics (as reported in the profiler).
    Collider mesh cooking is enabled and all the meshes are referenced.
    The object has unit scale.

    When I try to instantiate a prefab instead, it takes too long too.

    What should I do to ensure, that the collider mesh does not need to rebake every single time?

    Thanks for any tips.

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class ReplacePart : MonoBehaviour
    6. {
    7.     public GameObject replacement;
    8.  
    9.     public void Replace()
    10.     {
    11.         transform.parent = null;
    12.         GameObject g = gameObject;
    13.         {
    14.             var r = g.AddComponent<Rigidbody>();
    15.             r.mass = 2;
    16.         }
    17.         {
    18.             var mf = g.AddComponent<MeshFilter>();
    19.             mf.sharedMesh = replacement.GetComponent<MeshFilter>().sharedMesh;
    20.         }
    21.         {
    22.             var mr = g.AddComponent<MeshRenderer>();
    23.             var mrc = replacement.GetComponent<MeshRenderer>();
    24.             mr.lightProbeUsage = mrc.lightProbeUsage;
    25.             mr.reflectionProbeUsage = mrc.reflectionProbeUsage;
    26.             mr.shadowCastingMode = mrc.shadowCastingMode;
    27.             mr.receiveShadows = mrc.receiveShadows;
    28.             mr.sharedMaterial = mrc.sharedMaterial;
    29.         }
    30.         {
    31.             var mc = g.AddComponent<MeshCollider>();
    32.             var mct = replacement.GetComponent<MeshCollider>();
    33.             mc.cookingOptions = mct.cookingOptions;
    34.             mc.convex = mct.convex;
    35.             mc.sharedMesh = mct.sharedMesh;
    36.         }
    37.         Destroy(GetComponent<SkinnedMeshRenderer>());
    38.         Destroy(gameObject, Random.Range(5f, 15f));
    39.         Destroy(this);
    40.     }
    41. }
    42.