- Home /
Adding to delegate with multiple instances of the same object
So I have a set of reset functions to be called when a player dies like so:
public delegate void ResetFunction();
public ResetFunction resetFunctions;
Certain objects have their own reset functions added to this using something like this:
GameManager.resetFunctions += ResetObstacle;
Generally, this has been working great. However, I'm now building scenes that have multiple instances of the same types of objects, say an "obstacle", so there are multiple components adding their own ResetObstacle function to the list of delegates. However, when running resetFunctions, only one instance of each type of function appears to be getting called, so one "obstacle" object will be reset, but the rest will not. Does anyone know why and/or know a way to resolve this kind of thing?
Also, on a semi-related note, I was doing this in an attempt to not have to reload an entire scene when the player dies (which is likely to happen very often). However, perhaps Unity optimizes things enough that reloading the current scene isn't as intensive as, say, loading a new scene. If anyone knows anything about this, I'd be interested as well as it could alleviate the need for these reset functions altogether.
Any help is greatly appreciated. Thanks!
Answer by fafase · Feb 24, 2018 at 06:49 PM
I am not sure I get it right but it seems you want one instance to inform all others of the same type about something happening.
One simple way is to use static event:
public abstract class BaseClass: MonoBehaviour
{
public delegate void BroadcastMessage(object sender, string message);
public static event EventHandler BroadcastMessage = null;
protected virtual void Start()
{
BroadcastMessage += ProcessBroadcast;
}
protected abstract void ProcessBroadcast(object sender, string message) ;
}
public abstract class MyItem: BaseClass
{
protected override void ProcessBroadcast(object sender, string message) ;
{
if(sender == this){ }
switch(message){
case "Death":
break;
}
}
private void DamageItem(int damage){
this.health -= damage;
if( this.health < 0){ BroadcastMessage(this, "Death"); }
}
}
In this concept, the MyClass type inherits and implements the ProcessBroadcast. You can have any type inheriting and taking part in the broadcast process.
Because the event is static, it is handled at class level (BaseClass) so any BaseClass object will get the message and can handle it in their own way.
Thanks fafase. This got me working. I still think there's something inherently wrong with how I'm using delegates or something, but since this got me moving forward, I think it's the best answer.
Your answer
Follow this Question
Related Questions
Game behaves differently when it restarts 1 Answer
Loading Specific Scenes Post-Build 0 Answers
Capture reference to recently loaded scene asycn 0 Answers
Multiple scenes 2 Answers
UI canvas or panel that only appears once per game session? 1 Answer