- Home /
Collision Detection
I'm trying to detect what object my character is colliding with. My simple block of code is always giving me "null" back.
function OnCollisonEnter (theCollision : Collision)
{
/*if(theCollision.CompareTag == "Floor")
{
grounded = true;// Sets grounded variable to true.
//Debug.Log(theCollision.tag);
}
*/
print(theCollision);
}
As you can see the end result would be to detect to tag and use that but it doesn't even seem to be dectecting what object it collides with. I'm using a rigidbody on cube hitting another cube. I'm super new but any help would be greatly appreciated.
With OnCollisionEnter, you have to call the collider of the collision, so try: print(theCollision.collider);
Answer by DryTear · Feb 26, 2013 at 12:39 AM
private var objectCollided : string;
function OnCollisionEnter(objectCollided : Collision)
{
//if(objectCollided.gameObject.tag == "BlaBla")
//{
//Do Something
//}
//print(objectCollided.gameObject.tag);
//Debug.Log(objectCollided.gameObject.tag);
}
function OnGUI()
{
GUILayout.Label(Rect(Screen.width/2, Screen.heigth/2,0,0), "Collided With "+objectCollided);
}
Answer by AutoFredrik · Feb 24, 2013 at 10:56 AM
"theCollision" stores collision data, not the actual object you collided with. As Coreyf716 said you need to use Debug.Log(theCollision.collider.tag);
to get the tag of the object you collided with. Also, I think you're using CompareTag wrong. Try if(theCollision.collider.CompareTag("Floor"))
. Once again, you were trying to get the tag of the collision data, not the object you collided with. This stuff can be a bit confusing if you're new. :) I think this should work. Good luck!
Thanks, When I do that I get this error:
NullReferenceException: Object reference not set to an instance of an object Boo.Lang.Runtime.RuntimeServices.GetDispatcher (System.Object target, System.String cache$$anonymous$$eyName, System.Type[] cache$$anonymous$$eyTypes, Boo.Lang.Runtime.DynamicDispatching.DispatcherFactory factory) Boo.Lang.Runtime.RuntimeServices.GetDispatcher (System.Object target, System.Object[] args, System.String cache$$anonymous$$eyName, Boo.Lang.Runtime.DynamicDispatching.DispatcherFactory factory)
Which was getting before when i had it as if(theCollision.tag = "Floor") (or a number of other ways I tried)