Hello everyone,
I need some help please. I am making an fps and using delegates in script. I want to kill some zombies, it works fine at first but when one of the zombies is dead, whenever I shoot another one, I get an error telling me that I can"t access the health component because it was destroyed.
Here my code for the health script:
public class ZombieHealth : MonoBehaviour {
public delegate void EnemyKilled(GameObject gameObject);
public static event EnemyKilled OnEnemyKilled;
public int zombieHealth = 50;
// Use this for initialization
void Start () {
GUIMaster.OnFireButtonPressed += Shoot;
}
// Update is called once per frame
void Update () {
}
void EnemiesKilled(GameObject gameObject){
if(OnEnemyKilled!=null){
OnEnemyKilled(gameObject);
}
}
void Shoot(bool isHit,GameObject hitZombie, int damage){
if(isHit&&hitZombie.GetInstanceID() == gameObject.GetInstanceID()){
hitZombie.GetComponent<ZombieHealth>().zombieHealth-=damage;
if(hitZombie.GetComponent<ZombieHealth>().zombieHealth<=0){
EnemiesKilled(hitZombie);
}
}
}
}
This is the code of the triggered event from the GUIMaster script, that the ZombieHealth script is listening to:
void Shoot(){
if(OnFireButtonPressed!=null){
if(Physics.Raycast(ejectingPort,out hit,10f,layerMask)){
OnFireButtonPressed(true,hit.transform.gameObject,mainWeaponDamage);
}else{
OnFireButtonPressed(false,null,0);
}
}
}