Search Unity

NetworkManager Error: Server client disconnect error: 1

Discussion in 'Multiplayer' started by newwise, Nov 2, 2016.

  1. newwise

    newwise

    Joined:
    Mar 14, 2016
    Posts:
    7
    Error on Unity 5.4.2f2 Personal

    1. Created New Application - "Server"

    а) Created Scene
    b) Add NetworkManager component on Camera
    c) Add NetworkManagrHUD component on Camera
    d) off "AutoCreatePlayer"

    2. Created New Application - "Client"
    same a) b) c) d)

    3. Run "Server Only" and run "Client" in two different applications

    4. Connection is completed, but when close "Client" application then error on "Server":

    Server client disconnect error:1
    UnityEngine.Networking.NetworkIdentity:UNetStaticUpdate()
    OnDisconnectError error:6
    UnityEngine.Networking.NetworkIdentity:UNetStaticUpdate()


    Event "public override void OnServerDisconnect (NetworkConnection conn)" don't execute

    I don't have code, only have components.

    Why this error? Help please.
     
    Last edited: Nov 2, 2016
    Lohoris2 likes this.
  2. Deleted User

    Deleted User

    Guest

    As I know, it will be fixed on 5.4.3
     
  3. newwise

    newwise

    Joined:
    Mar 14, 2016
    Posts:
    7
    who knows when 5.4.3?
     
  4. l3fty

    l3fty

    Joined:
    Mar 23, 2013
    Posts:
    87
  5. newwise

    newwise

    Joined:
    Mar 14, 2016
    Posts:
    7
    Install patch 5.4.2p3, last error is fixed, but new error:

    ServerDisconnected due to error: Timeout
    UnityEngine.Networking.NetworkIdentity:UNetStaticUpdate()
     
    Anisoropos and CGDever like this.
  6. Deleted User

    Deleted User

    Guest

    Still have the same error on 5.4.2 p3;
     
  7. LittleRainGames

    LittleRainGames

    Joined:
    Apr 7, 2016
    Posts:
    97
    I have 5.4.2 and I get these two errors.

     
  8. Deleted User

    Deleted User

    Guest

  9. LittleRainGames

    LittleRainGames

    Joined:
    Apr 7, 2016
    Posts:
    97
    Ahh thank you kind sir.
     
    Deleted User likes this.
  10. Lohoris2

    Lohoris2

    Joined:
    Aug 20, 2013
    Posts:
    85
    I got this error on 5.5.0f3.
     
    isidro02139 likes this.
  11. l3fty

    l3fty

    Joined:
    Mar 23, 2013
    Posts:
    87
    This is the method from Unity's networking source (NetworkManager.cs for 5.4 branch) that you'll want to override in your network manager:

    Code (CSharp):
    1.  
    2. public virtual void OnServerDisconnect(NetworkConnection conn)
    3. {
    4.     NetworkServer.DestroyPlayersForConnection(conn);
    5.     if (conn.lastError != NetworkError.Ok)
    6.     {
    7.         if (LogFilter.logError)
    8.         {
    9.              Debug.LogError("ServerDisconnected due to error: " + conn.lastError);
    10.         }
    11.     }
    12. }
    13.  
    Then you can handle the errors however you want to :)
     
  12. fafase

    fafase

    Joined:
    Jul 3, 2012
    Posts:
    163
    Ok but I would think that the issue is that the error happens in the first place not how to avoid the printing.

    For my part, my server randomly goes off what would go in the override?
     
    Anisoropos likes this.
  13. LoadingHome

    LoadingHome

    Joined:
    Jan 8, 2015
    Posts:
    43
    Same issue here with unity 5.4.2. With Unity 5.4.3 I get this error:
    I don't have any of this issues with Unity 5.4.1, but in that version the editor is unstable, crashes and bugs that later versions don't have. It's a bit uncomfortable working with 5.4.1.
     
  14. fafase

    fafase

    Joined:
    Jul 3, 2012
    Posts:
    163
    We have been witnessing major issues with basic apps running on UNET with Unity 5.5.

    Using Hololens, any device may disconnect quite regularly.

    Also, having 3 clients (one server) and one common object only (NetworkTransform), the system will quickly throw an error claiming to many data are being sent (Can't remember the message wording).

    Also, I see often tutorials testing with a build running aside the editor on the same computer. Works fine but the same code on different devices and you get some authority errors. Actually, my code was faulty but it would not tell me.

    I would think that since messages were all coming with same ip address, the program is not able to make the difference between the server and the client.

    Finally, as we are using Hololens, it is often not anchoring properly or only after 2 to 5min. That time is long enough to actually lose the connection so basically it is not really happening.
     
    isidro02139 likes this.
  15. LoadingHome

    LoadingHome

    Joined:
    Jan 8, 2015
    Posts:
    43
    "ServerDisconnected due to error: Timeout". Same error when client disconnects on Unity 5.5.1f1
     
  16. zee_ola05

    zee_ola05

    Joined:
    Feb 2, 2014
    Posts:
    166
    I'm also getting "ServerDisconnected due to error: Timeout" on Unity 5.5.1p1
     
  17. Paradoks

    Paradoks

    Joined:
    Oct 13, 2009
    Posts:
    436
  18. aabramychev

    aabramychev

    Unity Technologies

    Joined:
    Jul 17, 2012
    Posts:
    574
    @Paradoks, check please with 5.4 which we published here (see newtransport release) 5.6.0 will contain all of these changes. Beside this, it is difficult to say without reproducing this bug, is it timeout caused by internal bug, caused by wrong configuration (Confid,NetDropThreshold should be set to 80, and probably OverflowThreshold should be increased) or real timeout when server or client doesn't receive any packet for DisconnectTimeout period.
     
  19. LoadingHome

    LoadingHome

    Joined:
    Jan 8, 2015
    Posts:
    43
    It's still happening with Unity 5.6.0b11
     
  20. lluo

    lluo

    Joined:
    May 19, 2016
    Posts:
    20
    [Error] ClientDisconnected due to error: Timeout

    Unity version 5.5.2p1 personal 64bit (iPhone 5S)
     
  21. Rodolfo-Rubens

    Rodolfo-Rubens

    Joined:
    Nov 17, 2012
    Posts:
    1,197
    5.6.0b10 builds and I'm getting this error!
     
  22. Rodolfo-Rubens

    Rodolfo-Rubens

    Joined:
    Nov 17, 2012
    Posts:
    1,197
    Well, I'm done with unity networking, 0 support from UT. I also noticed that 5.6 had only 9 changes/fixes/improvements related to networking.
     
  23. Deleted User

    Deleted User

    Guest

    Is it really hard to ignore Disonnect Error?
     
  24. Rodolfo-Rubens

    Rodolfo-Rubens

    Joined:
    Nov 17, 2012
    Posts:
    1,197
    It's not just an error, the player gets disconnected and goes back to the lobby scene after like 10 seconds. I just decided to go with photon.
     
  25. aabramychev

    aabramychev

    Unity Technologies

    Joined:
    Jul 17, 2012
    Posts:
    574
    disconnect by timeout happened if one of the peer does not receive anything from another peer for a disconnect timeout. Most probably you have default disconnect timeout = 2000 ms (2 sec) and working in WiFi environment, where jitter can be > 2 sec. Set this value to 5000 (5 sec) and try again.

    If you persistently has this disconnection regardless LAN/WiFi/WAN do you use is it a bug or something wrong with code.

    Question: Did you open the bug about this issue? If yes could you provide its number please?
     
    zubz likes this.
  26. LoadingHome

    LoadingHome

    Joined:
    Jan 8, 2015
    Posts:
    43
    Is clearly a bug. It does not happen in version 5.4.1f, and it begins to happen from that version onwards. The error occurs on the server when a user disconnects normally. Please fix, I want to use unity 5.6 but this bug prevents me for use it.

    Edit: To clarify, in my case the clients do not disconnect by timeout. But if a client voluntarily disconnects, server prints this error:

    ServerDisconnected due to error: Timeout
    UnityEngine.Networking.NetworkIdentity:UNetStaticUpdate()
     
    wlwl2 likes this.
  27. aabramychev

    aabramychev

    Unity Technologies

    Joined:
    Jul 17, 2012
    Posts:
    574
    @LoadingHome Hmm, imagine that you download file from web server, and I suddenly switch this server off. What's happened? You will disconnected. So, what is the bug here?

    The disconnect send in unet is one packet. So when you call disconnect, client will send one disconnect packet to server and then will return to your disconnectEvent. If server will receive this event it will return disconnectEvent and error = OK, if packet will lost, server will disconnect client by timeout, and you will receive the same disconnect event too. So, it is not clear for me what should be fixed here? Can you clarify this?
     
    Deleted User likes this.
  28. LoadingHome

    LoadingHome

    Joined:
    Jan 8, 2015
    Posts:
    43
    @aabramychev I will try to explain it, Although I think the problem is fairly well described throughout this thread.
    English is not my native language, so sorry if something is not well explained.

    In Unity 5.4.1f1 when you start a server game, a client connects and after a while leaves the game voluntarily. The player gameobject is deleted by the server and no error message is printed in console. Until here everything is ok.

    In unity 5.4.2 when a player leaves the game, server prints differents errors as stated by another user in this thread, besides the server doesn't delete the players gameobjects after disconnects, but all this was fixed in version 5.4.2p3.

    The problem is that since that version at the time the player leaves the game, the server prints this new error message: "ServerDisconnected due to error: Timeout"

    Yes, now the gameobject of the player is correctly deleted from the server and everything seems to be fine, but if unity did not ever print this error in console when a player exit from game and now it does, it gives me to think that something is wrong since 5.4.2p3. Maybe still related with the 5.4.2 net issues?

    I can ignore this error, but I do not know what other problems could provoke in the game.
    If you tell me, as a unity developer, that this is normal and from now on server will always print this error then ok, but it seems strange to me.
     
    Last edited: Apr 5, 2017
  29. Deleted User

    Deleted User

    Guest

    Seems like that problem is fully fixed in 5.5+.
    But don't forget to backup your 5.4 project, because 5.5 use a new serialization method for prefabs.
     
  30. LoadingHome

    LoadingHome

    Joined:
    Jan 8, 2015
    Posts:
    43
    Unity 5.6 still have this issue...
     
  31. Deleted User

    Deleted User

    Guest

    Hm, I'm on 5.5 p4, and don't have this one. Strange..
     
  32. aabramychev

    aabramychev

    Unity Technologies

    Joined:
    Jul 17, 2012
    Posts:
    574
    OK, let me try to explain what's going on:
    1. You send disconnect message (call Disconnect functions)
    2. Disconnect message placed in the socket queue
    3. you kill client
    4. socket closed too
    5. library cannot send disconnect ...
    why it happens now? library changing, so different time requires for disconnect to be sent and for socket to be closed...
    why we leave this message, sometimes is useful to understand what's going on.
     
  33. LoadingHome

    LoadingHome

    Joined:
    Jan 8, 2015
    Posts:
    43
    Then as I understand from now on, due to changes in the network library, we will see this message on server when a player disconnects and close the client. Ok then I can upgrade the unity version.

    As feedback I consider that this message on server can be confusing and that like me, some may be interpreting it as a bug. Nor will we be able to distinguish whether a player has actually been disconnected by timeout or because he has simply left the game.
     
    Last edited: Apr 6, 2017
    Seathan, Deleted User and aabramychev like this.
  34. aabramychev

    aabramychev

    Unity Technologies

    Joined:
    Jul 17, 2012
    Posts:
    574
    Yes I agreed. I don't like this very much too. The problem is - i haven't yet found better and simpler solution for this. Do not really want to do tcp like disconnect... :(
     
    wlwl2 and Seathan like this.
  35. scottlaforge

    scottlaforge

    Joined:
    Mar 12, 2013
    Posts:
    42
    Thanks for the clarification on this problem. I see this disconnect error on a regular basis and have been constantly looking for a way to fix the "bug," thinking that it is a problem in my code. Instead, if I understand correctly, it is because someone has either left the game or from a true timeout. And, it is because a message was not able to make a complete round trip? Feels like this message should appear as a warning or as a normal log message and not as an error, if this is the case.
     
    wlwl2, Seathan and tanapp like this.
  36. aabramychev

    aabramychev

    Unity Technologies

    Joined:
    Jul 17, 2012
    Posts:
    574
    @scottlaforge yes, you are right. I think we need something like:
    if(debugLog)
    printf("timeout .... ");
    will add in todo list
     
  37. MyFunFair11

    MyFunFair11

    Joined:
    Jan 12, 2015
    Posts:
    4
    I'm using Unity 2017.1, this bug still exist.

    1. server/host start game
    2. a client join the game
    3. client close the game
    4. server receive client disconnect, and kill the client's player object
    5. server receive "ServerDisconnected due to error: Timeout" error
     
    wlwl2 and Lohoris2 like this.
  38. mischa2k

    mischa2k

    Joined:
    Sep 4, 2015
    Posts:
    4,347
    This happens because NetworkManager.OnServerDisconnect throws an error if lastError != NetworkError.Ok.
    If you want a fix, check out HLAPI Pro. It's as simple as not throwing errors in case of NetworkError.Timeout - since that happens all the time anyway.
    upload_2017-8-30_9-52-29.png
     
    Deleted User likes this.
  39. damnSimpleGames

    damnSimpleGames

    Joined:
    Oct 13, 2017
    Posts:
    13
    This error still exists on 2017.3 ...
     
    Fattie likes this.
  40. IMemeManI

    IMemeManI

    Joined:
    May 4, 2017
    Posts:
    2
    ^
     
    Fattie likes this.
  41. TamBui

    TamBui

    Joined:
    Jun 29, 2017
    Posts:
    9
    I am also getting this on 2017.3.0f3. When I call NetworkManager.instance.StopClient() from my client to disconnect it from my host, the host gets an error that states:

    ServerDisconnected due to error: Timeout
    UnityEngine.Networking.NetworkIdentity:UNetStaticUpdate()

    What is the proper workaround handling of this error? Any help would be appreciated.
     
    Fattie likes this.
  42. mischa2k

    mischa2k

    Joined:
    Sep 4, 2015
    Posts:
    4,347
    Try this: https://forum.unity3d.com/threads/unet-hlapi-pro-taking-unet-to-the-next-level.425437/
     
  43. Homicide

    Homicide

    Joined:
    Oct 11, 2012
    Posts:
    657
    The code provided above by member is exactly how you fix this error, which IS still occurring in current version.

    Code (CSharp):
    1. public virtual void OnServerDisconnect(NetworkConnection conn)
    2. {
    3.     NetworkServer.DestroyPlayersForConnection(conn);
    4.     if (conn.lastError != NetworkError.Ok)
    5.     {
    6.         if (LogFilter.logError)
    7.         {
    8.              Debug.LogError("ServerDisconnected due to error: " + conn.lastError);
    9.         }
    10.     }
    11. }
    Just override it, whoila...

    HOWEVER, upon changing to client in editor mode, and having my android phone hosting a LAN game, i discovered that when the server just pulls the pin and kills game, in the editor, the client experiences exact same issue...

    ClientDisconnected due to error: Timeout
    UnityEngine.Networking.NetworkIdentity:UNetStaticUpdate()

    This one i have not been able to locate a fix for yet.
     
    Fattie likes this.
  44. Homicide

    Homicide

    Joined:
    Oct 11, 2012
    Posts:
    657
    Actually, i just did find it in the source code release... fixed with this method override, again...

    Code (CSharp):
    1.     public override void OnClientDisconnect(NetworkConnection conn)
    2.     {
    3.         StopClient();
    4.     }
    What i find funny, is that the code INSIDE the editors libraries must not be matching what is shows as the source code. Hmm, just a mess.
     
    Fattie and TamBui like this.
  45. cra_unity

    cra_unity

    Joined:
    Mar 27, 2015
    Posts:
    3
    This seems to still be an issue? I'm unable to get my clients to disconnect without seeing the
    nityEngine.Networking.NetworkIdentity:UNetStaticUpdate()
    errors
     
    Fattie likes this.
  46. Fattie

    Fattie

    Joined:
    Jul 5, 2012
    Posts:
    476
    Just for anyone googling here, perhaps new to Unity networking .....

    Unity give you as a built-in a NetworkManager. However it ....... doesn't work.

    This is hugely typical of Unity / Unity documentation.

    In the examples and so on, it will say things like "Just add a NetworkManager !"

    In simple reality though, it literally doesn't work at all.

    1. You very simply, cannot, use the supplied NetworkManager. It's that simple.

    2. There are (at least) four functions which you must provide (that is to say, override in c#) to get a basic demo working.

    See example listing below.

    Note that this is only the most basic example to actually "make it work in a demo". You face many, many problems.

    Just one notable issue is that - surprise ! - Unet does not by default eliminate the abstract player items (i.e. the spawned prefabs) of a thing when it disconnects. In some game milieu, you do want that behavior, but it's surprising that it is the unmentioned default. The function NetworkServer.DestroyPlayersForConnection destroys - that is to say on every client still connected - two things, the abstract player item of the lost player, and, any/all authority objects which the lost player had previously, during the game, had created (ie, as described in this post at Section 4, Example 2. {Note that, if indeed it IS the nature of your game that you DO want to keep the 'ghost' player in there, that involves considerable work as to tracking it and perhaps allowing the same actual human to re-take control of it, if/when that human again connects.}

    Also in particular see the posts of @Homicide / Obiwan above for more useful info.

    So who disconnected?

    In any real-world scenario, when there's a disconnect, you'll need to of course know "which thing" or "which user" disconnected.You simply cannot do networking without this, but it is NOT, repeat NOT built-in to unet in any way. You have to program this completely manually from scratch.There is a general example of that at the bottom, see below.

    Functions poorly named ...

    (In Unity ? No, really?)

    "OnServerDisconnect" means "here on the server, we have learned that someone has disconnected"

    and

    "OnClientDisconnect" means "here on one of the clients, we have learned that the server has disappeared"

    You may ask

    But why does it just crash?

    There's a rational reason - in c# you can not enforce an abstract-like override need. This is an everyday feature of the language. (You can see endless discussion of this, example ) It's quite normal in such cases to just "force the program to crash". IE, if your colleagues have forgotten the override, we know it simply and literally won't work without the override (you must provide the function in question, or the app just doesn't work), so it's perfectly reasonable to "just crash". In that way, during development, your colleagues know what's going on. So that's what's happening here.

    But.

    If Unity had simply added in the error text "You must override OnClientDisconnect" then none of this massive problem would ever have arisen.

    That is what you do on any team when you force a crash because of a missing function that must be written as an override. You just have a 3-word message for your colleagues ... "you forgot BlendRobotArm". It's a basic.

    The thousands of words of garbage doco and examples on Unity networking could all be replaced with the short sentence "BTW, NetworkBehaviour doesn't work, you must write your own code for these four functions ..."

    That's ALL that is needed to know. :/

    Code samples....

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.Networking;
    5.  
    6. public class OurNetworkManager : NetworkManager {
    7.  
    8.     public override void OnServerConnect(NetworkConnection nc) {
    9.  
    10.         base.OnServerConnect(nc);
    11.  
    12.         int cid = nc.connectionId;
    13.         int hid = nc.hostId;
    14.  
    15.         LogDisplay.Log("server: on server connect " + cid + " " + hid);
    16.     }
    17.  
    18.     public override void OnClientConnect(NetworkConnection nc) {
    19.  
    20.         base.OnClientConnect(nc);
    21.         // ** critical ** you must stop your client discovery RIGHT HERE,
    22.         // directly after the call to the base.  you actually can NOT do it
    23.         // in your discovery client
    24.  
    25.         int cid = nc.connectionId;
    26.         int hid = nc.hostId;
    27.  
    28.         LogDisplay.Log("client! on client connect " + cid + " " + hid);
    29.     }
    30.  
    31.     public override void OnClientDisconnect(NetworkConnection nc) {
    32.  
    33.         Log .. this means HERE ON A CLIENT, the server has disappeared
    34.  
    35.         // 1. You certainly want to do this:
    36.         StopClient();
    37.  
    38.         // 2. Almost certainly, you will seek a new server ...
    39.         // using your own code, you will basically again launch your DiscoveryClient
    40.     }
    41.  
    42.     public override void OnServerDisconnect(NetworkConnection nc) {
    43.  
    44.         Log .. this means, HERE ON THE SERVER, one of our clients has disappeared
    45.  
    46.         // 1. you will absolutely have to keep track of your connections
    47.         Grid.SetToNull(nc);
    48.  
    49.         // 2. it is usually absolutely essential to do this ...
    50.         // (if you do wish to keep a 'ghost' player going, that is far more difficult)
    51.         NetworkServer.DestroyPlayersForConnection(nc);
    52.     }
    53.  
    54. }
    (
    Important aside:

    (ONE) For late 2018, you must stop your client discovery as shown above in the network manager in OnClientConnect, specifically directly after the call to the base. You actually can NOT do it in the discovery client as you would assume.


    (TWO) AND there is a racetrack bug in Unity which allows the discoverer to be called more than once even when you turn it off; you have to manually add a lock boolean: see discovery client script below.
    )


    Continuing .. How do you know "which" thing disconnected?

    You must anyway have some sort of (say) singleton which keeps track of your connections.

    As each thing connects, you must save somewhere that connection so you know who is who. (Notice "connection_OC1" etc below.)

    You may well ask, how does each new connecting client identify itself to the server? That's entirely up to you. (A great example of something that is totally non-optional - you Must Do It - but, surprise, it's not in Unet.) Here's an example in a static, LAN, case of something like that .. ("OurNet" is our own standard base typical networking material.)

    Code (CSharp):
    1.     public void OurNetIdentifySelfToServer() {
    2.         CmdOurNetIdentifySelfToServer( Hardware.whatAmIText );
    3.     }
    4.  
    5.     [Command]
    6.     void CmdOurNetIdentifySelfToServer(string connectingClientIdString) {
    7.         LogDisplay.Log("on server .. OurNetIdentifySelfToServer .. >" + connectingClientIdString + "<");
    8.         if (connectingClientIdString == "oculus 1") { Grid.connection_OC1 = connectionToClient; }
    9.         .. etc
    10.         .. etc
    11.  
    You would (must) call "OurNetIdentifySelfToServer" in "OnStartLocalPlayer()" in your NetworkBehavior.

    Again, and this is very confusing to new networkers, it's utterly "up to you" to do this (absolutely basic, essential) thing of "keeping track of all the connections and being able to identify which is which."

    When something disconnects, use a routine something like "Describe" below to look up which one it was. (You may well have a hash, array, or whatever, this example was a fixed LAN case.)

    Code (CSharp):
    1.  
    2. using UnityEngine;
    3. using UnityEngine.Networking;
    4.  
    5. static class Grid {
    6.  
    7.     // for networking ..
    8.  
    9.     public static Comms commsLocalPlayer;
    10.     public static Comms commsTheServer;
    11.  
    12.     public static NetworkConnection connection_OC1;
    13.     public static NetworkConnection connection_OC2;
    14.     public static NetworkConnection connection_OC3;
    15.     public static NetworkConnection connection_OC4;
    16.     public static NetworkConnection connection_OC5;
    17.     public static NetworkConnection connection_OC6;
    18.     public static NetworkConnection connection_UserKiosk;
    19.  
    20.     public static string Describe(NetworkConnection nc) {
    21.  
    22.         if (nc == connection_OC1) return "oc1";
    23.         if (nc == connection_OC2) return "oc2";
    24.         if (nc == connection_OC3) return "oc3";
    25.         if (nc == connection_OC4) return "oc4";
    26.         if (nc == connection_OC5) return "oc5";
    27.         if (nc == connection_OC6) return "oc6";
    28.         if (nc == connection_UserKiosk) return "oc6userKiosk";
    29.         return "??UNKNOWN NETWORK CONNECTION??";
    30.     }
    31.  
    32.     // you definitely need to be able to un-set these, when, something disconnects
    33.  
    34.     public static string SetToNull(NetworkConnection nc) {
    35.  
    36.         if (nc == connection_OC1) connection_OC1 = null;
    37.         if (nc == connection_OC2) connection_OC2 = null;
    38.         if (nc == connection_OC3) connection_OC3 = null;
    39.         if (nc == connection_OC4) connection_OC4 = null;
    40.         if (nc == connection_OC5) connection_OC5 = null;
    41.         if (nc == connection_OC6) connection_OC6 = null;
    42.         if (nc == connection_UserKiosk) connection_UserKiosk = null;
    43.         return "??UNKNOWN NETWORK CONNECTION?? in SetToNull";
    44.     }
    45.     ...
    And here then is the matching client discovery, which works perfectly with the network manager above.

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.Networking;
    5.  
    6. public class NetworkDiscoveryClient: NetworkDiscovery {
    7.  
    8.     // in the case of client discovery, there's a unity bug (late 2018)
    9.     // where on some hardware, OnReceivedBroadcast will be called more
    10.     // than once even if you "stop" the discoverer.
    11.     // so you have to do this:
    12.     bool hasRecievedBroadcastAtLeastOnce = true;
    13.  
    14.     void Awake() {
    15.    
    16.         // it's extremely likely you will have to keep track of this
    17.         // both game object and component, in some global location
    18.         Grid.theNetworkDiscoveryGameObject = gameObject;
    19.         Grid.theNetworkDiscoveryClient = this;
    20.     }
    21.  
    22.     // a network discovery custom script can be either a client or a server
    23.     // to make it one or the other, simply call "startAs .." on launch or relaunch
    24.  
    25.     // you often have to "turn on again" a discovery process (ie, when the server
    26.     // disappears and you want to start looking for a server again)
    27.     // hence you must use OnEnable rather that Awake or Start
    28.  
    29.     protected void OnEnable() {
    30.    
    31.         if (.. during development, you want to use 'localhost' ..) {
    32.             OnReceivedBroadcast("localhost", "");
    33.             return;
    34.         }
    35.    
    36.         Initialize();
    37.         hasRecievedBroadcastAtLeastOnce = false; // must do this precisely here
    38.         StartAsClient();
    39.     }
    40.  
    41.     public override void OnReceivedBroadcast(string fromAddress, string data) {
    42.    
    43.         // deal with Unity bug, see notes above
    44.         if (hasRecievedBroadcastAtLeastOnce) {
    45.             YourLog("+++ avoided Unity racetrack bug, cool eh? would have crashed otherwise");
    46.             return;
    47.         }
    48.         hasRecievedBroadcastAtLeastOnce = true;
    49.    
    50.         YourLog("in client discovery. found server .. fromAddress");
    51.    
    52.         // you now want to turn off discovery
    53.         // (as needed, it will get turned on again in YourNetworkManager#OnClientDisconnect)
    54.    
    55.         // intriguingly you CAN NOT DO IT HERE ... due to yet another Unity bug
    56.         // you must do it in YourNetworkManager#OnClientConnect IMMEDIATELY after base.
    57.         // see the notes in red in this forum post up above
    58.         // StopBroadcast(); .. can not do this here
    59.    
    60.         NetworkManager networkManager = Object.FindObjectOfType<NetworkManager>();
    61.         if (networkManager == null) { .. you forgot the network manager .. return; }
    62.    
    63.         // to start the client, simply do these two things:
    64.         networkManager.networkAddress = fromAddress;
    65.         networkManager.StartClient();
    66.    
    67.         gameObject.SetActive(false);
    68.         // if the server disappears, you'll start discovery again simply
    69.         // by re-enabling this gameobject
    70.     }
    71.  
    72. }
    73.  
    Here is the matching NetworkDiscoveryServer

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.Networking;
    5.  
    6. public class NetworkDiscoveryServer: NetworkDiscovery
    7. {
    8.  
    9.     void Start() { // become a discovery-server
    10.        
    11.         // a network discovery custom script can be either a client or a server
    12.         // to make it one or the other, simply use the "StartAs .." call inside the
    13.         // ordinary MonoBehavior "Start" call.
    14.        
    15.         NetworkManager networkManager = Object.FindObjectOfType<NetworkManager>();
    16.         if (networkManager == null) {
    17.            
    18.             LogDisplay.Log("BAD SET UP - you totally forgot a NetworkManager");
    19.             return;
    20.         }
    21.        
    22.         ///networkManager.StartServer();
    23.         networkManager.StartHost();
    24.        
    25.        
    26.         if (Grid.developmentUseLocalhost) {
    27.            
    28.             LogDisplay.Log("dev .. localhost style server, no discovery");
    29.             return;
    30.         }
    31.        
    32.        
    33.         Initialize();
    34.        
    35.         StartAsServer();
    36.         LogDisplay.Log("as server .. start discovery");
    37.     }
    38.    
    39.    
    40.    
    41. }
    42.  
     
    Last edited: Nov 2, 2018
  47. Sylker

    Sylker

    Joined:
    Sep 22, 2012
    Posts:
    22
    @Fattie, you're a lifesaver! I was running in circles with this 'host id out of bound' problem for quite a while until I found your post. I'm new to all this networking thing on Unity and problems like this can be really frustrating. I'm not getting how the Grid class works tho. I would appreciate if you develop it more in details. Thanks for sharing.
     
  48. Fattie

    Fattie

    Joined:
    Jul 5, 2012
    Posts:
    476
    Hi @Sylker - I'm really glad it helped. That was a really long post and I'm glad it helped someone! :)

    The`Grid` class is nothing more than a singleton - if you're new to programming, just think of it as a "global".

    You can access it "directly" and easily from anywhere.

    Notice it's a "static class" instead of the usual "class", and it doesn't have the usual ": MonoBehavior" thingy!

    I do give the full code for `static class Grid` up above!

    It's simply "a singleton" - like a global you can access anywhere. But be aware it's not a MonoBehavior - it has nothing to do with any game object, it's "just a class" sitting in space!

    Let me know if that clears it up.

    Be aware of this issue .. https://stackoverflow.com/questions...-script-works-only-one-time/35891919#35891919 .. in any real unity project you have a preload scene, and then, you have the various "universal" parts of your project that only exist once, and, you must access from anywhere. Consider things like sound effects, connections to a server, scoring and AI systems. You need a way to "easily access those from anywhere" and indeed you do that with a singleton - and it's usually called "Grid". (Like "the power grid" of a country or something.) So that's why it's called "Grid.cs" !
     
  49. Salazar

    Salazar

    Joined:
    Sep 2, 2013
    Posts:
    235
  50. Fattie

    Fattie

    Joined:
    Jul 5, 2012
    Posts:
    476
    @Salazar , unfortunately it is abandoned, apparently

    The first unity networking was so bad it was comic

    The "current" Unet is trash.

    Apparently they are having another go - a totally new one is coming.

    They're not going to waste any more time on the current one, so it's unlikely anyone will bother with the doco on the current trash. It's so bad doco doesn't help anyway.
     
    Joe-Censored and Salazar like this.