- Home /
Get objects in collision
I need to detect if the object that has collided with my player is a bullet. Then I can change the health and so on.
void OnCollisionEnter(Collision collision) {
Debug.Log("Collision");
}
This works well. Is there any way I can get both objects participating in a collision?
Answer by Eric5h5 · Jan 26, 2012 at 07:45 PM
The object that the script is attached to is one of the objects participating in a collision, and collision.gameObject is the other.
@Eric5h5 ok thanks. Is there any way I can deter$$anonymous$$e if collision.gameObject has the "Bullet" script attached to it?
You probably want to use tags, but if for some reason that's not possible, you can check whether collision.gameObject.GetComponent(Bullet) is null.
@Eric5h5 What if there's more than one bullet in the air? Won't a tag return any one of those bullets?
@Davste depends what you are checking. If the bullets are hitting you one at the time(like bullets would) then no, it will only return the newest bullet that struck you.
The Collision variable in OnCollisionEnter can only return the object involved in the collision, it can't just pick random objects from anywhere.