- Home /
Collision detection between two objects?
I used this code:
void OnCollisionEnter(Collision Collider){
if(transform.collider.gameObject.tag == "dna"){
DNA += 1.0f;
Destroy(collider.gameObject);
}
}
The expected outcome is that when the object this script is on touches an object with the "dna" tag, it will add to the "DNA" variable, and destroy the object with the "dna" tag. Neither of these things work, any ideas or suggestions?
Answer by ScroodgeM · Aug 26, 2012 at 04:46 PM
void OnCollisionEnter(Collision collision){ if(collision.collider.gameObject.tag == "dna"){ DNA += 1.0f; Destroy(collision.collider.gameObject); } }
first:
if(collider.gameObject.tag == "dna"){
instead of
if(transform.collider.gameObject.tag == "dna"){
transform is local transform. not an object comes to collider
second:
Collision Collider in input params and collider (started from lower case) are different things 8)
use Collision collision on input to avoid mixing and coll, and check collision.collider inside method
Thanks, I tried this too and it didn't work, it's only that way from me trying to figure out why it doesn't work.
It still doesn't work. Literally no effect to it. Thanks though.
Did you check my answer. you should have rigidbodies for this message OnCollisionEnter to be sent at all. also tags are case sensitive.
insert Debug.Log("hit") at method body start to check if collision happens.
Answer by Ashkan_gc · Aug 26, 2012 at 05:29 PM
Actually to read the information of the object that you've collided with you should read data of the object which is passed to the function using collider variable as scroodge said. you should compare it's tag to the value and not your own. When you use transform.gameObject.tag you are getting the reference of your own transform (the object which script is attached to) and then it's gameObject and tag properties. Also the objects should have none kinematic rigidbodies for this to work (at least one of them if i remember correctly). refer to the collision table in manual pages for colliders for more info about this.