- Home /
Collision On Specific Object= Destroy not working.
Hello, so I put together a script that would destroy the object that has the script if it hits the player. However, the object does not break. The script is
pragma strict
function OnCollisionEnter (hit : Collision) { if(hit.transform.gameObject.name == "Player") { Destroy(gameObject); } }
My game is 2D. The name of the player is simply Player. I am quite new to Scripting and Unity so all help is appreciated.
You've made 2 additional posts after this one describing the same problem: "Collision not working". So there's no need to make duplicate posts. Try to use better grammar in post titles. Also for courtesy, you should format your code with the "code button" so it's readable. This will help you get answers in the future.
Answer by vintar · Feb 22, 2015 at 05:01 AM
should be OnCollisionEnter2D :)
Getting the error
Script error: OnCollisionEnter2D This message parameter has to be of type: Collision2D The message will be ignored.
Answer by Jessespike · Feb 22, 2015 at 09:16 AM
Rename your function:
//function OnCollisionEnter (hit : Collision)
function OnTriggerEnter2D(hit : Collider2D) // if using 2D Colliders
function OnTriggerEnter(hit : Collider) // if you're using normal Colliders
Both game objects need a Collider (Such as BoxCollider2D).
The non-player collider will need "Is Trigger" to true. Non-player object will also need your script.
The player object will need a RigidBody, set "Is Kinematic" to true;
Thank you for both of your responses. I will take note of the first one, but I just to clarify I was extremely tired at the time of the posting. Also I have done everything you had advised me to do but the object is falling through the player and the floor for some reason.
Only the player needs a rigidbody, remove the rigidbody from the other objects.
Your answer
Follow this Question
Related Questions
Collision On Object Error. Please help. 1 Answer
Scaling Script? 1 Answer
Problem creating a script to destroy object on collision. 1 Answer
Transform.localPosition Script Problem. 3 Answers
Duplication Problem. Please help. 2 Answers