- Home /
Destroy Scripting Help
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);
}
}
Answer by aldonaletto · Oct 22, 2011 at 12:22 PM
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
There's an error saying
"method not found: UnityEngine.Collision.Send$$anonymous$$essage"
Can you please help?
aldonaletto made a mistake! Replace that line with
myCol.transform.Send$$anonymous$$essage("Damage", 20, Send$$anonymous$$essageOptions.DontRequireReceiver);
As @syclamoth said, I forgot the object reference - it should be:
myCol.transform.Send$$anonymous$$essage(...);
or
myCol.gameObject.Send$$anonymous$$essage(...);
Or any other object component referenced in myCol. I fixed that in the answer.
Your answer
Follow this Question
Related Questions
Enemy's wont die if spawned 1 Answer
Destroy enemy using raycasts 2 Answers
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
Enemy Follow Script Help 2 Answers
Need help with enemy spawner 2 Answers