Add boxcollider2d in runtime?

I am making a 2d platformer where I want to be able to put out a cube with a boxcollider on on a certain keypress.

This is the current code:

using UnityEngine;
using System.Collections;



public class KillScript : MonoBehaviour {
    public BoxCollider2D sc;



    void Update() {
        if(Input.GetKey(KeyCode.Q)) {
            var pos = Input.mousePosition;
            pos.z = 10;
            pos = Camera.main.ScreenToWorldPoint(pos);
            GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
            cube.gameObject.AddComponent<BoxCollider2D>();
            cube.transform.position = pos;
        }
    }





void OnTriggerEnter2D(Collider2D other)
    {
        if (other.tag == "platform") {
            Debug.Break();
            }
                }
    }

Right now, it spawns the object and puts it in the correct area, but the boxcollider isnt added.

Why?

Solved it.
Cloned an existing block instead, worked better.

1 Like

The info message that you get when you try this tells you why: “Can’t add component ‘BoxCollider2D’ to Cube because it conflicts with the existing ‘BoxCollider’ derived component!” The cube primitive already has a box collider and you can’t mix that with a 2D box collider. So you’d either have to destroy that and add the BoxCollider2D instead, or create the object another way such as instantiating prefabs (which would be better).

–Eric

You could make a prefab, instead of cloning a existing block.

In the start function load the prefab with resources.Load or insert it via a public var in the inspector.
The when you need it use GameObject.Instantiate on the object.
The advantage here is that if there are no blocks in the scene this is still working!

Good luck on your project!