- Home /
Prevent fire event from all instances.
This is my event manager:
public class Event_Mgr
{
public delegate void Power_State();
public static event Power_State On_Power_Enabled;
public static void Power_Enabling()
{
if (On_Power_Enabled != null) On_Power_Enabled();
}
}
In script "Systems_Controller" at start method i write: Event_Mgr.Power_Enabling(); this fire event. In script "Movement" that subscribed to event i write:
void OnEnable()
{
Event_Mgr.On_Power_Enabled += Enable_Movement;
}
void OnDisable()
{
Event_Mgr.On_Power_Enabled -= Enable_Movement;
}
I have for example 2 instances of gameobject and each of them contain both scripts: "Systems_Controller" and "Movement". So as result i see that event fire twice for each instance. Question how make event to be fired only for same instance, not to all instances that subscribed to that event. Maybe event not best option for this? I have player wehicle and enemy wehicle so both need to enable power before they can move. But when i enable power on player, event triggered for both player and enemy. Then when enemy enable power event triggered also for both player and enemy.
"Quetion how make event to be fired only for same instance, not to all instances that subscribed to that event"
This is not clear, do you want Script A and B to be called only on object A or object A and B to receive the call but only for one script?
no, problem that event "static" by its nature so this lead to trigger event on all instances that subscribed to event. I have player wehicle and enemy wehicle so both need to enable power before they can move. But when i enable power on player, event triggered for both player and enemy. Then when enemy enable power event triggered also for both player and enemy because event "static".
Answer by fafase · Jul 06, 2015 at 08:46 AM
Ok so first off the reason why it calls everyone is not due to the static, it is due to the fact that an event calls all listeners, static is different topic.
Since, your player and enemy are registered, they get called. If you nee the event to select the listeners, two ways, first most likely, you should have two listeners, one for player and one for enemy (or other items).
Second way, not so good, pass a parameter to your event to define what should happen.
On_Power_Enable(ObjectType.Player);
void On_Power_Enable_Listener(ObjectType typeObject){
if(typeObject != myType){return;}
}
But as you can see it requires extra computation that may lead to error or unwanted behaviour later on.
I think first method not an option because i can have more that 1 enemy at same time, so problem will not spread only on player. Second method looks not bad, because i not have alternative yet. Thanks anyway fafase