Search code examples
unity-game-engineunity3d-mirror

Server function doesn't appear to be running on Server


I have a 2 player game that runs in a host-client setup that has a startup sequence that should only be run when both players are connected.

public class NetworkGovernor : NetworkManager
{
public override void OnServerAddPlayer(NetworkConnectionToClient conn)
{
    base.OnServerAddPlayer(conn);
    AssignPlayer(conn);
    if (numPlayers > 1)
    {
        PlayerManager P1 = Governor.instance.P1.GetComponent<PlayerManager>();
        PlayerManager P2 = Governor.instance.P2.GetComponent<PlayerManager>();
        P1.RpcLoadData();
        P2.RpcLoadData();
        P1.RpcStartSequence();
        P2.RpcStartSequence();
    }
}

public void AssignPlayer(NetworkConnectionToClient conn)
{
    NetworkIdentity networkIdentity = conn.identity;
    if (Governor.instance.P1 == null)
    {
        Governor.instance.P1 = networkIdentity;
        Debug.Log("branch 1");
        Debug.Log(Governor.instance.P1);
    }
    else
    {
        Governor.instance.P2 = networkIdentity;
        Debug.Log("branch 2");
        Debug.Log(Governor.instance.P1);
    }
}
}

I have a class called Governor that is a singleton instance and has two variables to store the network identities of the players. This script is attached to the same GameObject as the NetworkGovernor (at the root of the scene). For context, the class is setup like this:

public class Governor : MonoBehaviour
{
public static Governor instance { get; private set; }
.
.
.
public NetworkIdentity P1;
public NetworkIdentity P2;
private void Awake()
{
    if (instance == null)
    {
        instance = this;
        DontDestroyOnLoad(gameObject);
    }
    else
    {
        Destroy(gameObject);
    }
}
}

The expectation is that OnServerAddPlayer is run on the Server, so the instance of Governor is the same when both players join. However, when both clients join (or more specifically, when the host joins followed by the client), the log shows that branch 1 was run both times (resulting in a null pointer at P2.RpcLoadData();). Either my understanding of how the networking works is wrong or there is some incorrect wiring somewhere, but how to I make the server execute the AssignPlayer such that it results in both branch 1 and branch 2 being run?


Solution

  • The above does work as expected, but I had another script PlayerManager that had

    [Server]
    public override void OnStartServer()
    {
        Governor.instance.P1 = null;
        Governor.instance.P2 = null;
    }
    

    Which, unexpectedly, seems to run after each call of OnServerAddPlayer.