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

Pretty much title. I use C# by the way.

Use gameObject.AddComponent(), see Unity - Scripting API: GameObject.AddComponent for more information.

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.

    void GhostMesh()
    {

        MeshCollider gCollider = currMesh.GetComponent<MeshCollider>();

        MeshCollider TempGCollider = mcTEST.AddComponent(gCollider) as MeshCollider;

    }

I keep getting this error: “gCollider is a variable but is used like a type”.

MeshCollider MeshCollida;






  

void GhostMesh()
    {
        MeshCollida = gameObject.AddComponent<MeshCollider>();
        MeshCollida.convex = true;
    }
1 Like

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

MeshCollida.isTrigger = "true";

Let me know if it worked.