How would I go about scripting that if a bullet prefab collides with an enemy say 5 times the enemy will destroy itself? Ive already wrote out a script that destroys an object called enemy when the bullet prefab collides with it but im not sure about rest of it, can anyone help me?
here’s the script
function OnCollisionEnter(myCol: Collision){
if(myCol.gameObject.name == "enemy"){
Destroy(myCol.gameObject);
The traditional way to do that is to have a Damage function in the enemy, and call it with SendMessage in the bullet script.
Modify the bullet script as follows:
function OnCollisionEnter(myCol: Collision){
if(myCol.gameObject.name == "enemy"){ // comparing tags would be safer!
// call the function Damage(20) in the enemy
myCol.gameObject.SendMessage("Damage", 20, SendMessageOptions.DontRequireReceiver);
}
Destroy(gameObject); // destroy the bullet to avoid multiple hits
}
And attach this code to the enemy script:
var health = 100;
function Damage(dmg: int){
health -= dmg; // reduce health
if (health <= 0){ // if health has gone...
Destroy(gameObject); // enemy suicides
}
}
It would be better to compare tag instead of name: when Unity instantiates some object, it appends “(clone)” to the name, thus you may end with a new enemy called “enemy (clone)”, which will not be recognized by the bullet script and become as indestructible as the SuperMan.