- Home /
Error with 2d collision detection
I'm very new to Unity, so I'm guessing this is something easy to fix. Anyways the problem is that I have two 2d objects, both have 2d box colliders and one has a 2d rigidbody, but they do not register when they collide. I am not even getting the debuglog to print. I have the collision code attached to the bullet and the bullet also has the rigidbody. The code is
var move : int = 2;
function OnCollisionEnter2D(thing : Collision)
{
if(thing.gameObject.tag == "destructible"){
Destroy(thing.gameObject);
Destroy(this.gameObject);
Debug.Log("hit!");
}
}
function Update() {
var y = Time.deltaTime * move;
this.transform.Translate(0, y, 0);
}
Oh and the error message I receive is "Script error: OnCollisionEnter2D This message parameter has to be of type: Collision 2D"
Answer by Li0nSword · Mar 28, 2014 at 10:28 PM
From the error you mentioned you simply have to change the variable type from Collision to Collision2D like so
function OnCollisionEnter2D(thing : Collision2D)
{
Also i'm not 100% sure but I don't think the debug.log will print as you print it AFTER destroying the object itself.
Answer by Key_Less · Mar 28, 2014 at 09:57 PM
Since you are detecting 2D collisions, your OnCollisionEnter2D method needs a parameter of type Collision2D to report back with the 2D information of the object that has collided.
function OnCollisionEnter2D(thing : Collision2D)
{
}
Thanks! That got it working better, I ran into a new error now though. It's saying NullReferenceException: Object reference not set to an instance of an object.. And neither the bullet nor the enemy are being destroyed
Could you post your updated code and the error message with it please?
var move : int = 5;
function OnTriggerEnter2D(thing : Collider2D){
if(thing.tag == "destructible"){
Debug.Log("hit!");
Destroy(thing.gameObject);
Destroy(this.gameObject);
}
}
function Update() {
var y = Time.deltaTime * move;
this.transform.Translate(0, y, 0);
if(this.transform.position.y > 8){
Destroy(this.gameObject);
}
}
That's the finished code, but I got it working finally. I just had to rearrange a few things and remove the ".gameObject.tag" part in the if statement. Thanks a bunch though.
Your answer
Follow this Question
Related Questions
How to make 2D sprite character stop jittering when running into walls? 2 Answers
How to run a collision between 2 objects only once 1 Answer
Character Controller Collisions Question 1 Answer
how to make object follow mouse cursor while detecting collision 1 Answer
shader change alpha around collision 1 Answer