- Home /
Problem with delegates C#
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);
}
}
}
Answer by troien · Nov 05, 2014 at 04:39 PM
When you subscribe to a event, don't forget to unsubsribe. Otherwise you'll try to call the delegate on a component that has been destroyed... (And you'll probably get memory leaks)
Adding this should work.
void OnDestroy()
{
GUIMaster.OnFireButtonPressed -= Shoot;
}
Your answer
Follow this Question
Related Questions
Delegates with parameters 3 Answers
Delegate an event 2 Answers
Cloud recognition in Vuforia 0 Answers
I can't download Unity engine 1 Answer