Search Unity

Mesh Collider works only sometimes

Discussion in 'Physics' started by Mastrix, Aug 18, 2019.

  1. Mastrix

    Mastrix

    Joined:
    Nov 22, 2018
    Posts:
    1
    Why does this Mesh Collider only works when its deactivated in void Awake() and reactivated in Start()?
    I tried to generate Terrain and i found out if i add the Mesh Collider right in the beginning its works just fine but if i place it after the math for the height calculation i must reactivate it in Start(). (Code is to long for here)

    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public class Test : MonoBehaviour
    4. {
    5.     void Awake()
    6.     {
    7.         Mesh mesh = new Mesh();
    8.         Vector3[] vertices = new Vector3[3];
    9.  
    10.         vertices[0] = new Vector3(0, 0, 0);
    11.         vertices[1] = new Vector3(0, 0, 10);
    12.         vertices[2] = new Vector3(10, 0, 10);
    13.  
    14.  
    15.         int[] triangles = { 0, 1, 2 };
    16.  
    17.  
    18.         gameObject.AddComponent<MeshFilter>().mesh = mesh;
    19.         gameObject.AddComponent<MeshCollider>()/*.enabled = false*/;
    20.         gameObject.AddComponent<MeshRenderer>();
    21.  
    22.  
    23.  
    24.         mesh.vertices = vertices;
    25.         mesh.triangles = triangles;
    26.         mesh.RecalculateNormals();
    27.  
    28.         GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
    29.         cube.transform.position = new Vector3(2.5f, 3, 7);
    30.         cube.AddComponent<Rigidbody>();
    31.     }
    32.  
    33.     void Start()
    34.     {
    35.         //gameObject.GetComponent<MeshCollider>().enabled = true;
    36.     }
    37. }
    38.  
     
  2. Grizmu

    Grizmu

    Joined:
    Aug 27, 2013
    Posts:
    131
    After editing your mesh try to call mesh.UploadMeshData. It should fix having to deactivate and activate the Mesh Collider component which uses the edited mesh.