I want to create a Instance of the Player script. Here is an example of a script that I found online. This code works perfectly, the 'Local Instance' is really a local instance, meaning that the Player of each client does its own things while the other Players do theirs:
'''
public class Player : NetworkBehaviour
{
public static Player LocalInstance { get; private set; }
public static event EventHandler OnAnyPlayerSpawned;
public override void OnNetworkSpawn()
{
if (IsOwner)
{
LocalInstance = this;
}
OnAnyPlayerSpawned?.Invoke(this, EventArgs.Empty);
}
}
'''
Other classes will access that instance, here is one of them:
'''
public class EquipPlayer : MonoBehaviour
{
void Start()
{
if (Player.LocalInstance != null)
Player.LocalInstance.OnLoadEquipData += Player_OnLoadEquipData;
else
Player.OnAnyPlayerSpawned += Player_OnAnyPlayerSpawned;
}
private void Player_OnAnyPlayerSpawned(object sender, EventArgs e)
{
if (Player.LocalInstance != null)
{
Player.LocalInstance.OnLoadEquipData -= Player_OnLoadEquipData;
Player.LocalInstance.OnLoadEquipData += Player_OnLoadEquipData;
}
}
}
'''
I do not understand
a) why, in the code right above, the class EquipPlayer subscribes to the event any time a new Player is spawned by other clients. Should it do it only when the Player of its own client is spawned ??
b) why it first unsubscribes from the event and the subscribes again ? The official explanation is 'to avoid to have multiple listeners'. Can anyone explain this in simple words ?