"Missing Collider2D"

I’m having some trouble with a 2D box collider. right now, I’ve pared it down to this very simple code:

void Update () {
		Debug.Log (this.collider2D.collider.bounds.center);

When I try to run this, I get the following error:

"MissingComponentException: There is no ‘Collider’ attached to the “New Sprite game object, but a script is tryign to access it. You probably need to add a collider to the game object “New Sprite”. Or your script needs to check of the component is attached before using it.”

As of right now, “New Sprite” is the ONLY object I have, aside from the Main Camera. So, it’s not as though I’ve accidentally put the collider on a parent or child of it. What’s causing this error and how can I fix it so that I can make use of the object’s collider? I can switch it out for a 3D box collider and the above code works just fine.

Unity tries to make it easy to reference GameObjects and their components. Every component has shortcuts to find built-in components, such as renderers, rigidbodies, colliders, animations, particles, and more. Finally, there’s the GetComponent function, which lets you find any component type (including your own).

You can think of these as roughly equivalent:

this.collider2D //gets attached Collider2D component (or null)

this.GetComponent<Collider2D>() //gets attached Collider2D component (or null)

Which means that this:


Is a lot like doing this:

Collider2D c2d = this.GetComponent<Collider2D>();
collider c = c2d.GetComponent<Collider>();

It compiles, but there’s almost no way that makes sense: even supposing you had both colliders attached, why wouldn’t you just grab the one reference directly? I can imagine no reason to reference both types like that.

Collider and Collider2D do similar things, but they can’t be used interchangeably. One works with 3D mechanics, the other works with 2D mechanics (which are new in Unity 4).

Most likely scenario here is that you’ve confused your collider types. It’s important to keep straight whether you’re handling 2D or 3D.

You’re actually trying to access a 3D Collider (just known as Collider) as a child of a 2D collider. I see why you did this, because you wanted the bounds, and you found it there. Unity provides a bounds object for Collider objects but not for Collider2D objects.

Can you just use the transform.position instead of collider center, or is there a specific need for this?

Since the 2D colliders are fairly new, I think this is a Unity bug, because it seems like 2D colliders should also provide a bounds object. But it’s easy to work around:

	BoxCollider2D coll = GetComponent<BoxCollider2D> ();
	Vector2 cntr = coll.center;