Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

How do I assign a MeshCollider to a gameobject via code?

Discussion in 'Physics' started by Ninamori, May 18, 2016.

  1. Ninamori

    Ninamori

    Joined:
    Oct 30, 2015
    Posts:
    33
    Pretty much title. I use C# by the way.
     
  2. EnricoBC

    EnricoBC

    Joined:
    May 4, 2014
    Posts:
    20
  3. Ninamori

    Ninamori

    Joined:
    Oct 30, 2015
    Posts:
    33
    Thanks. However...

    I'm probably doing something stupid but bare with me as I've never really messed with meshs or this sort of thing.

    Code (csharp):
    1.  
    2.     void GhostMesh()
    3.     {
    4.  
    5.         MeshCollider gCollider = currMesh.GetComponent<MeshCollider>();
    6.  
    7.         MeshCollider TempGCollider = mcTEST.AddComponent(gCollider) as MeshCollider;
    8.  
    9.     }
    10.  
    I keep getting this error: "gCollider is a variable but is used like a type".
     
    Last edited: May 18, 2016
  4. nitentei

    nitentei

    Joined:
    Mar 11, 2016
    Posts:
    59



    Code (csharp):
    1.  
    2.  
    3. MeshCollider MeshCollida;
    4.  
    5.  
    6.  
    7.  
    8.  
    9.  
    10.  
    11.  
    12. void GhostMesh()
    13.     {
    14.         MeshCollida = gameObject.AddComponent<MeshCollider>();
    15.         MeshCollida.convex = true;
    16.     }
    17.  
     
    Last edited: May 18, 2016
    memBrain likes this.
  5. nitentei

    nitentei

    Joined:
    Mar 11, 2016
    Posts:
    59
    if it's the object the script is on that you're adding the component to, you don't need to edit this any more than just putting line 3 up there with your variables before the first Void line, probably "void Start () {". (called a Method, btw)

    The reason your last script didn't work out is because GetComponent grabs a Component already added to the object to change its settings. Even after the first time you use AddComponent you don't need to use Get Component after. Just keep using the MeshCollida variable.

    an example would be

    Code (CSharp):
    1. MeshCollida.isTrigger = "true";






    Let me know if it worked.
     
    Last edited: May 18, 2016