0
votes

I am creating a cube in script(c#). I want to remove the BoxCollider since i am developing a 2D game and exchange it through the BoxCollider2d. Then i want to add a RigiBody2D and show the cube in my world. The Problem is that i always get the error:

Can't add component 'BoxCollider2D' to Cube because it conflicts with the existing 'BoxCollider' derived component! UnityEngine.GameObject:AddComponent() CreateCube:OnCollisionEnter2D(Collision2D) (at Assets/Scripts/CreateCube.cs:15)

I get this error but the Code works anyways. BUT it only goes till the line Destroy(cube.collider); and thats it! The BoxCollider is defenitly removed correctly cause when i take a look at the created objects it is gone. I really dont know why the compiler is telling me that there is a existing BoxCollider.

using UnityEngine;
using System.Collections;

public class CreateCube : MonoBehaviour
{
    void OnCollisionEnter2D(Collision2D coll)
    {
        // Create Cube
        GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);

        // Destroy BoxCollider
        Destroy(cube.collider);

        // Add BoxCollider2D
        cube.AddComponent<BoxCollider2D>();

        // Add RigiBody2D
        cube.AddComponent<Rigidbody2D>();

        // Show Cube in World
        cube.transform.position = new Vector3(0, 0.5f, 0);
    }
}

Has anyone an idea?

1
you should probably not create a Cube primitive but a 2D sprite to begin withLearnCocos2D

1 Answers

2
votes

Destroy will always wait until after the current Update loop to remove the component, so the Collider is not removed when you are adding the BoxCollider2D. Use DestroyImmediate instead.

However I would recommend to create a prefab with the things you want and use Instantiate instead. Like this:

// Create Cube
GameObject cube = Instantiate(yourPrefab, new Vector(0, 0.5f, 0), Quaternion.identidy) as GameObject;