- Home /
 
Problem creating a script to destroy object on collision.
Hello. I am new to both Game Creation and Scripting, so all help is very much appreciated. I am trying to create a script that, when my object collides with my player, will destroy the object. The code I have made is #pragma strict
 function OnCollisionEnter (hit : Collision) { 
     if(hit.transform.gameObject.name == "Player") { 
         Destroy(gameObject); } 
 }
 
               I tried to make this code as simple as possible, but it doesn't work. When the object hits the player it just stacks on top of him.
Information about the game: The game I have created is intended to be mobile and 2D. Both the object and player have Rigidbody2D applied. The object has the script I have shown. Both objects have colliders.
Sorry for the long post but I wish to complete this game as fast as I can. If you have any questions just ask. Thank you.
Answer by maccabbe · Feb 28, 2015 at 12:54 AM
Objects with 2D rigidbodies and 2D colliders need to use OnCollisionEnter2D(Collision2D coll) instead of OnCollisionEnter(Collision coll).
Try using the following to make sure a collision would be detected
 function OnCollisionEnter2D(coll: Collision2D) {
     Debug.Log(coll.gameObject.name);
 }
 
              Your answer
 
             Follow this Question
Related Questions
Collision On Specific Object= Destroy not working. 2 Answers
Scaling Script? 1 Answer
Transform.localPosition Script Problem. 3 Answers
Collision On Object Error. Please help. 1 Answer
Duplication Problem. Please help. 2 Answers