- Home /
Collision script
In my project I have a cube and spheres falling from the sky. I want the spheres to destroy the cube on collision, Here is my script attatched to the sphere:
function OnCollisionEnter ( collision : Collision) {
if (collision.collider.gameObject.Find("Player"))
Destroy (GameObject.Find("Player"));
}
The problem here is the sphere destroys the cube whenever it hits any rigidbody. What am I doing wrong?
Answer by Mike 3 · Jul 13, 2010 at 07:45 PM
it should be:
function OnCollisionEnter ( collision : Collision)
{
if (collision.gameObject.name == "Player")
Destroy (collision.gameObject);
}
So you check what collided, then destroy it if it's called Player
Your original code just checked if there was an object called player, then destroyed it
Awesome thank you so much! So I take it collision.gameObject means the object that the collision occurred with?
Yep it does. Added benefit is that it won't destroy a player object at random if you have two objects called Player
Answer by Daniel 6 · Jul 13, 2010 at 07:45 PM
try this:
function OnCollisionEnter ( collision : Collision) {
if (collision.collider.name == "Player")
Destroy (GameObject.Find("Player"));
}
Your code was checking if an object (called "Player") even existed in the whole scene. But mine checks if specifically the colliding object's name is "Player".
Beat me by 2 seconds for the last question, 13 seconds for this one... damn you ;) +1 anyways (though using find to destroy the player is better done via collision.gameObject)
Your answer
Follow this Question
Related Questions
How to call on collision enter only once 3 Answers
Collision of two Gameobjects 0 Answers
OnCollisonEnter2D not working 0 Answers
OnTrigger bullet with multiple colliders on enemy 1 Answer
OnCollisionEnter If statement error 1 Answer