- Home /
How do I get the player and the object they touch both disappear/destroyed?
I'm new to unity and have very little programming experience. I'm trying get my character to disappear when he collides with a enemy/game object. I looked at some of others people suggestions/vidoes and I don't think I doing it right. My game looks similar to ,1945, in that the enemy is moving from the top down. I got the player to move and it just goes through the enemy. I have "Player", "Enemy1", and "Enemy2" in my hierarchy and each of them has a collider (sphere/cube) . What script should I use?
Answer by Garazbolg · Nov 12, 2015 at 04:51 PM
You should use OnCollisionEnter or OnTriggerEnter
They are natives messages callbacks (a function called by Unity) used when two objects both have a Collider. If your player go through the enemies i'm guessing you don't use Rigidbodies so you could just set the collider on your player or the enemies to isTrigger (that will simplify some calculs).
On your player or the enemies you can put a script (or add to a script if there already is one) this function :
/*Lets say you put this function on the player Script (better), if not just replace each 'EnemyScript' by your Player Script name*/
//Without IsTrigger
function OnCollisionEnter(collision: Collision) {
for (var contact: ContactPoint in collision.contacts) {
var enemy = contact.otherCollider.gameObject.GetComponent(EnemyScript);
if(enemy){
Destroy(enemy.gameObject);//Destroy the enemy
Destroy(gameObject);//Destroy the player
}
}
}
//With IsTrigger
function OnTriggerEnter (other : Collider) {
var enemy = other.gameObject.GetComponent(EnemyScript);
if(enemy){
Destroy(enemy.gameObject);//Destroy the enemy
Destroy(gameObject);//Destroy the player
}
}
Hope that helps you.
Your answer
Follow this Question
Related Questions
2D Collision not working! (child sprites colliders) 1 Answer
Ignore collision at high velocity. 1 Answer
Prefab instantiated by code, collision does not work 0 Answers
Compound collider object behaving as a whole? 1 Answer
Collision details 1 Answer