As I'm developing our game I have asked myself a couple times "When we have more than 1 player, how will I ensure events from player A do not crossover to player B?"
As an example, lets say player A clicks on a unit. This publishes an event with data on the click location, the type of object it is, and the player that clicked. This can be received by lets say a selection manager script that just keeps track of what is currently selected for that player.
The problem now, is that this event is received by every player. Every player will receive this event and try and select that object, and perform various tasks along the way.
Is there a method of programming in unity to ensure that an event is only subscribed to by classes that have the same player component referenced (only the appropriate players methods will be added to the invocation list of delegates under the player)? Or will I just need to create a check at the subscribers to these events to only accept the event data if it's the same player?
ie.
if ( RClickEventArgs.Player.GetInstanceID() == player.GetInstanceID()) {}
Edit: For clarity. Here is an example event.
public delegate void RightClickHandler(string clickType, RClickEventArgs e);
public static event RightClickHandler RightClickEvent;
private void RightClick()
{
if(Input.GetMouseButtonDown(1))
{
if (userInput.isMouseOnScreen && !EventSystem.current.IsPointerOverGameObject())
{
GameObject hitObject = inputValidations.FindHitObject();
Vector3 hitPoint = inputValidations.FindHitPoint();
hitPoint.z = -1;
if (hitObject && hitPoint != ResourceManager.InvalidPosition && hitObject.name != "Ground")
{
RightClickEvent("Object", new RClickEventArgs(hitObject, hitPoint, player));
}
else if (hitObject.name == "Ground")
{
RightClickEvent("Ground", new RClickEventArgs(hitPoint, player));
}
}
}
}
When an object is clicked an event is published with relevant info on what was clicked. There are subscribers to this event using "MouseClickEvents += YourMethodNameHere;". This works as intended. However, since two players will have the same scripts as components this creates an issue where the 2nd player's scripts also add themselves to the invocation list of player 1's delegates, and vice versa (as far as I know, I don't know how to check what is in the invocation lists). So each player receives their own events, and the events of the other player.
If I have a fundamental misunderstanding of a concept here, please let me know.