Hello,
I think I’ve finally grasped the basic idea behind delegates and events and I’m trying to introduce this mechanism to a test project I’m working on.
I have a Whatever prefab with a script which disables its own GameObject after a certain random period of time. I also have a Manager class (on an empty GameObject) which instantiates several Whatever prefabs at runtime and is notified of their demise via a standard method call (the prefab has a link to the Manager object through a public variable in the Editor). I tried to do that with events and delegate and was wondering if I was doing it right. Most tutorials I read and watched use a static event, so that’s what I tried first.
Inside the Whatever class, I have this (outside of Start or anything else, it’s at the top with the variable declarations):
public delegate void WhateverEventHandler(GameObject sender);
public static event WhateverEventHandler BugDeath;
Then, in the same class, when the prefab dies, I have this:
if (WhateverDeath != null)
{
WhateverDeath (this.gameObject);
}
In the Manager class, immediately after instantiating each prefab, I subscribe to the event with this:
Whatever.WhateverDeath += DeathHandle;
And a simple debugging method:
void DeathHandle(GameObject obj)
{
Debug.Log (obj.name + " had died");
}
Problem is each time a specific instance of the prefab dies, the DeathHandle() method gets called for each and every prefab instance in the scene. I presume this is because the event is being declared as static but I’m not sure I understand why this is happening.
Then I tried to make the event non-static by removing the static keyword and, in the Manager class, instead of referring to “Whatever.WhateverDeath” I used the event in each instance of the prefab, right after it’s been instantiated, like so (simplified, the whole thing is in a for loop which creates an object pool):
GameObject obj = Instantiate (WhateverPrefab, Vector3.zero, Quaternion.identity);
Whatever bc = obj.GetComponent<Whatever> ();
bc.WhateverDeath += DeathHandle;
This works, but I don’t understand exactly why. If I’m supposed to use events and delegates as an application-wide event system, should I somehow address the class directly, or is it normal to have a separate event for each instance of the class (which I think is what happening in the last example)?
Thanks a lot.