0
votes

I am instantiating a new game object with a Cube mesh. I'd like this to have a BoxCollider2D component.

I start by instantiating a new GameObject with a primitive using GameObject.CreatePrimitive. 'Creates a game object with a primitive mesh renderer and appropriate collider.'

GameObject inst = GameObject.CreatePrimitive(PrimitiveType.Cube);

A default BoxCollider (3D) is attached. I do not want this, so I remove it.

Destroy(inst.GetComponent<Collider>());

This works and in the editor I can see that I now have a cube with no BoxCollider.

Now I try adding a BoxCollider2D

inst.AddComponent<BoxCollider2D>();

The full method looks like this

private GameObject createSnakeCube()
    {
        GameObject inst = GameObject.CreatePrimitive(PrimitiveType.Cube);
        Destroy(inst.GetComponent<Collider>());
        inst.AddComponent<BoxCollider2D>();
        return inst;
    }

However. I will get the following error message

Can't add component 'BoxCollider2D' to Cube because 
it conflicts with the existing 'BoxCollider' derived component!    
UnityEngine.GameObject:AddComponent()

Does anyone know why Unity still thinks a BoxCollider is attached when none is visible in the editor?

1

1 Answers

1
votes

Destroy() will not immediately destroy the given object. It will mark it as to-be-deleted and will only delete all marked objects at the end of the frame as an optimization.

In your case you should use DestroyImmediate() which will immediately destroy the object, allowing you to add your new collider.