Search Unity

BUG or intended? OnServerReady, OnClientConnect. Inconsistencies...

Discussion in 'Multiplayer' started by Maisey, Dec 30, 2016.

  1. Maisey

    Maisey

    Joined:
    Feb 17, 2014
    Posts:
    302
    Hello,

    I've been struggling for this for a few hours now and can't manage to understand which order everything is called and if there's possibly a bug (or intended, which is hard to tell because documentation is lacking, to say the least).

    I'm trying to get a hold of a reference to the "Local Player"-object (LPo) inside a custom class which inherits from NetworkManager. But it seems that when I try to find this LPo I can't since (almost) all callbacks is invoked before it is even created. In some cases it works (see below).

    void OnServerConnect(NetworkConnection conn) <--- Inside this: (on server obviously)
    FindObjectsOfType<MyLocalPlayer>(); == null
    conn.playerControllers.Count == 0
    ClientScene.localPlayers == 0

    void OnServerReady(NetworkConnection conn) <--- Inside this: (on server obviously)
    FindObjectsOfType<MyLocalPlayer>(); == null
    conn.playerControllers.Count == 0
    ClientScene.localPlayers == 0

    void OnClientConnect(NetworkConnection conn) <--- Inside this: (this is special and what annoys me)
    FindObjectsOfType<MyLocalPlayer>(); == null (see below)
    conn.playerControllers.Count == 0 (see below)
    ClientScene.localPlayers == 0 (see below)

    The special case:
    If I'm host (and therefore are server and client at the same time), all will be good, for example, conn.playerControllers.Count will be 1 as it should be (and I can use it to get a hold of the LPo). But if I'm a connecting client (not host), the Count will be 0, and all other possible lists will also be empty. Which callback can I use to be sure that the LPo has been Instantiated (if I use the "auto-spawn player"-option)?

    I know there's an "easy" solution to this problem. For example, inside MyLocalPlayer.cs I can give the reference to the NetworkManager, but I don't want that kind of dependency. So, any help?

    So basically, inside CustomNetworkManager I want to do this (and for it to work on both the host and client):

    OnSomeCallback()
    {
    var player = conn.playerControllers[0].gameObject.GetCompontent<MyLocalPlayer>();
    }