- Home /
Object wont destroy on collision with another object
For some reason my object is not destroying when it collides with another object.
heres what im trying to do, my character is holding a sword, the sword object has a collider, so I want to destroy objects when only my sword collides with them so I put this script on my sword object:
function OnCollisionEnter (hit : Collision) {
if(hit.gameObject.tag == "Respawn") { //The object I want to destroy tag = Respawn
Destroy(hit.gameObject);
}
}
It doesn't work though. for testing purposes I removed the script from my sword and applied it to my character and changed the function to OnControllerCollider and it worked perfect, the only thing is thats not what Im trying to do, I don't want the object to destroy when the player touches it, I want it to destroy when the sword touches it. Im not sure why its not working when I use OnCollisionEnter and apply the script to my sword.
if it means anything, my sword is a child of my characters armature, so when my character moves his arm, the sword moves with it in the same direction. Maybe because its a child it could be causing the problem?
Other information, my sword just goes right through the object I want to destroy, but both the sword and the object I want to destroy have colliders on them.
Thanks for any help in advanced.
Answer by Posly · Jan 07, 2012 at 12:53 AM
You need a rigidbody on stuff that you want to detect collision on. Also if you don't want the enemy to be destroyed when the player just touches the sword I'd use an animation event, and in the animation event it creates a temporary trigger in front of your character and whatever is in that trigger will be destroyed. So let's say the person presses space it would play that animation and the animation event would create a temporary trigger box and just attach a OnTriggerEnter function onto the trigger box thingy and whatever is in that box will be destroyed. It's kinda confusing I guess but it would make the game more professional and stuff.
Thanks it worked, all I was missing the rigid body. I like the Trigger idea and yes that defiantly does sound a lot more professional. But to keep things simple ill just do it like this for now :)
Also I was thinking maybe to keep it even more simple I can achieve the same effect that you mentioned but with a different way.
I was thinking to disable the collider using collider.enabled = false;
and then using an If statment to check if the space key is pressed, if it is pressed then
collider.enabled = true;
then later it would set the collider back to false and only enable it to true when space is pressed, but for some reason that did not work,
the collider stays false even after I push space, not sure why.
Thanks anyway for the help.