- Home /
Destroy enemy using raycasts
Hi all, this script is attached to an invisible cube at the end of my gun it fires raycasts and if it hits anything in the scene it spawns a particle effect of sparks. If the rays collide with something with a tag of "Enemy" then it spawns a blood particle effect, this all works how it should apart from the ApplyDamage part which is supposed to destroy the enemy if its health goes to zero. This dosent work as my Enemy dosent have health and dosent know when to die, this is what I think anyway. Is my Enemy supposed to have a damage receiver sort of script which tells it when to destroy itself, I need some help with this can anyone lend a hand?
script
var amountOfShots = 30;
var reloadTime = 1.5;
var refireRate : float = 0.1;
function ShotPoller()
{
while(true)
{
if(Input.GetButton("Fire1"))
{
Shoot();
yield WaitForSeconds(refireRate);
}
if(Input.GetKeyDown("r")){
Reload();
}
yield;
}
}
function Start()
{
StartCoroutine(ShotPoller());
}
if(Input.GetKeyDown("r")){
Reload();
}
function Reload (){
yield WaitForSeconds(reloadTime);
amountOfShots = 30;
}
var shotSound : AudioClip;
var bloodPrefab : Transform;
var sparksPrefab : Transform;
var hit : RaycastHit;
var range = 500;
function Shoot (){
if(amountOfShots > 0){
amountOfShots--;
if(shotSound){
audio.PlayOneShot(shotSound);
}
if (shotSound) audio.PlayOneShot(shotSound);
var hit: RaycastHit;
if (Physics.Raycast(transform.position, transform.forward, hit)){
var rot = Quaternion.FromToRotation(Vector3.up, hit.normal);
if (hit.transform.tag == "Enemy"){
if (bloodPrefab) Instantiate(bloodPrefab, hit.point, rot);
hit.transform.SendMessage("ApplyDamage", 20, SendMessageOptions.DontRequireReceiver);
} else {
if (sparksPrefab) Instantiate(sparksPrefab, hit.point, rot);
}
}
}
}
Answer by Piflik · Apr 14, 2012 at 05:07 PM
I would simply add a public variable to the enemy called "health" and replace the "SendMessage" line at the end of your script with:
hit.GetComponent(EnemyScript).health -= 20;
The enemy would now have to test if his health is smaller than 0 and if so it would destroy itself.
Answer by bodec · Apr 14, 2012 at 01:46 PM
yes towards the bottom of your script where it says apply damage is your damage to your enemy that should be tied into a function on this script or another script that accesing the enemys health
Your answer
Follow this Question
Related Questions
Destroy Scripting Help 1 Answer
Enemy damage error 1 Answer
Enemy's wont die if spawned 1 Answer
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
Enemy Follow Script Help 2 Answers