Search Unity

  1. Get all the Unite Berlin 2018 news on the blog.
    Dismiss Notice
  2. Unity 2018.2 has arrived! Read about it here.
    Dismiss Notice
  3. Improve your Unity skills with a certified instructor in a private, interactive classroom. Learn more.
    Dismiss Notice
  4. ARCore is out of developer preview! Read about it here.
    Dismiss Notice
  5. Magic Leap’s Lumin SDK Technical Preview for Unity lets you get started creating content for Magic Leap One™. Find more information on our blog!
    Dismiss Notice
  6. Want to see the most recent patch releases? Take a peek at the patch release page.
    Dismiss Notice

Unity Multiplayer NetworkManagerHUD source

Discussion in 'Connected Games' started by seanr, Jun 14, 2015.

  1. seanr

    seanr

    Unity Technologies

    Joined:
    Sep 22, 2014
    Posts:
    669
    The NetworkManagerHUD is a good example of how to use the match maker system, including callbacks, and how to drive the NetworkManger from a UI. The NetworkManagerHUD doesnt use any internal functionality, just the public APIs.

    (this was posted to the beta forum earlier. reposting here).
     

    Attached Files:

  2. smitsc

    smitsc

    Joined:
    Mar 4, 2014
    Posts:
    4
    Is there a new 5.2 UI Canvas version ?
     
    i42-Xblade and Miscellaneous like this.
  3. Miscellaneous

    Miscellaneous

    Joined:
    Sep 24, 2013
    Posts:
    33
    Any link to C# source code for NetworkManager ? (would help understanding unet)
     
    K0Kos and wdruryzynga like this.
  4. WOODSY

    WOODSY

    Joined:
    Apr 8, 2015
    Posts:
    164
    Just add all the GUI bits that would usually be GUI buttons etc. and create new UI buttons and text fields by using 'using UnityEngine.UI'
     
  5. hakankaraduman

    hakankaraduman

    Joined:
    Aug 27, 2012
    Posts:
    319
    This doesn't work on 5.4, api is changed.

    Can you give the updated version or is there a detailed info about how to write custom network manager, matchmaking system and it's hud?

    Thanks
     
  6. rikey

    rikey

    Joined:
    Mar 3, 2015
    Posts:
    147
  7. Di_o

    Di_o

    Joined:
    May 10, 2016
    Posts:
    23

    Unity 5.4 doens't support the scipt like this anymore. Any chance to get the sourcecode to the new NetworkManagerHUD?
     
  8. rikey

    rikey

    Joined:
    Mar 3, 2015
    Posts:
    147
    laurachen and Di_o like this.
  9. bpaivalefou

    bpaivalefou

    Joined:
    Feb 5, 2016
    Posts:
    1
    Thank you so much !
     
  10. aaronfranke

    aaronfranke

    Joined:
    Jan 23, 2017
    Posts:
    9
    seanr, I found a bug in your code.

    if (NetworkServer.active && NetworkClient.active)
    {
    if (Input.GetKeyDown(KeyCode.X))
    {
    manager.StopHost();​
    }​
    }

    When connected as a client, it still says "Stop (X)", however, pressing X does not disconnect because the above code checks for both client and server being enabled. It should probably replaced with "NetworkServer.active || NetworkClient.active" as it is in the OnGUI method:

    if (NetworkServer.active || NetworkClient.active)
    {
    if (GUI.Button(new Rect(xpos, ypos, 200, 20), "Stop (X)"))
    {
    manager.StopHost();​
    }
    ypos += spacing;​
    }
     
  11. veereshkumbar

    veereshkumbar

    Joined:
    Aug 24, 2017
    Posts:
    4
    may i get a new custom NetworkManagerHUD.cs for new version of unity
     
  12. SavedByZero

    SavedByZero

    Joined:
    May 23, 2013
    Posts:
    37
    Which parts of the NetworkManager class are free? I know Matchmaker costs money, but what about StartHost / StopHost, and that general namespace? Not asking because I'm a cheapskate, but I'm doing a game for a client (as in, other person, not as in networking) and fees aren't an option for me for this.

    And ditto previous poster; OnGUI is antiquated and I'm surprised tutorial examples are still using it, though I suppose making prefabs and passing them around isn't easy.
     
  13. megabrobro

    megabrobro

    Joined:
    Jul 8, 2017
    Posts:
    70
    Anyone have an idea why Unity wouldnt just add a 'size' field, rather than us all having to write a custom UI?
     
    amit-chai likes this.
  14. JWLewis777

    JWLewis777

    Joined:
    May 17, 2015
    Posts:
    51
    You can create a server with StartServer() and create a client with StartClient() using NetManager. It took me a while to figure out how to set it up but I am very pleased with the outcome now. This isn't using any matchmaking services.
     
  15. megabrobro

    megabrobro

    Joined:
    Jul 8, 2017
    Posts:
    70
    Hi there, thanks for this insightful comment. Its helped me a bit but I am still struggling. Would you be kind enough to post a working example for me to work through and intergrate into my basic game please?

    I am half way through making a 2 player racing game but the online setup i have requires the user to put in their external IP and set up their own port forwarding
     
  16. SavedByZero

    SavedByZero

    Joined:
    May 23, 2013
    Posts:
    37
    Okay, what about NetworkDiscovery? I'm guessing...well, hoping that's free. That's the only way I can implement free LAN-based multiplayer functionality without forcing everyone to type in the host's IP address.
     
  17. wobes

    wobes

    Joined:
    Mar 9, 2013
    Posts:
    374
    megabrobro likes this.
  18. megabrobro

    megabrobro

    Joined:
    Jul 8, 2017
    Posts:
    70

    I hope so too. But because I am very new to networking in general its proving to be a real minefield of information
     
  19. megabrobro

    megabrobro

    Joined:
    Jul 8, 2017
    Posts:
    70

    Thank you for posting this! I will read through now and try to inwardly digest it.

    Please can you help me with a quick description exactly what that script is there to do? Thanks so much!!!

    EDIT: Sorry I just seen the 'Overview' lol. I will read through that also. I am really hoping this is for what I need it to be :)
     
  20. JWLewis777

    JWLewis777

    Joined:
    May 17, 2015
    Posts:
    51
    It took me awhile to figure out how to get a simple server and client running with minimal code and components. I was shooting for a very simple chat program since essentially thats what a multiplayer game is. It came down to the point of having to use Netmanager as a component to an empty game object. I didn't want to use the NetmanagerHUD, since a my chat client shouldn't have to input an IP address or port, it should start up and auto connect to chat server.

    In my server, I added an empty game object to scene, called it NetworkController, added the Netmanager component. I also have a button called ButHost, that will do the RunHost() on the Server.
    This is a condensed version of my code, I have textboxes, inputboxes, send message buttons to show messages from client and server.

    I then added both server and client scenes to build settings, ONLY clicked server and Built to UnityServerChat.exe for PC, then ONLY checked client scene and Built to UnityClientChat.exe for PC.

    The Debug.log statements will only show when running either the client or the server in the editor.
    Code (csharp):
    1.  
    2.  
    3. using System.Collections.Generic;
    4. using UnityEngine;
    5. using UnityEngine.Networking;
    6. using UnityEngine.UI;
    7.  
    8. public class Server_Controller : NetworkBehaviour {
    9.     public NetworkManager netManager;
    10.     private const short chatMessage = 131;
    11.     public Button butHost; //Set to host button in inspector and set onclick event to RunHost()
    12.     public Text butHostTxt; //Set to the text component of the host start button in inspector
    13.     public int hostID; //Not really used, just for showing hostID on button text when host started
    14.    
    15.  
    16.    // Use this for initialization
    17.    void Start () {
    18.         butHostTxt.text = "Start Host";
    19.  
    20.         if(!netManager){
    21.             //Grab the NetworkManager componenet
    22.             netManager = GetComponent<NetworkManager>();
    23.         }
    24.    }
    25.  
    26.     public void RunHost(){
    27.         if(!hostStarted){
    28.             netManager.maxConnections = 10;
    29.             netManager.networkPort = 7777;
    30.             netManager.StartServer();
    31.  
    32.             if(NetworkServer.active){
    33.                 Debug.Log("NetworkServer is active!");
    34.             }
    35.  
    36.             NetworkServer.RegisterHandler(chatMessage,ServerReceiveMessage);
    37.             NetworkServer.RegisterHandler(MsgType.Connect,ConnectRequest);
    38.             NetworkServer.RegisterHandler(MsgType.Disconnect,DisconnectRequest);    
    39.  
    40.             butHostTxt.text = "HostID: "+hostID+" - Stop Host";
    41.         }
    42.         else{
    43.             netManager.StopServer();
    44.             hostStarted = false;
    45.             butHostTxt.text = "Start Host";
    46.         }
    47.     }
    48.  
    49.     private void ServerReceiveMessage(NetworkMessage netMsg){
    50.         NetMessage tMsg = new NetMessage();
    51.         var tempMsg = netMsg.ReadMessage<NetMessage>();
    52.         tMsg.name = tempMsg.name;
    53.         tMsg.id = tempMsg.id;
    54.         tMsg.message = tempMsg.message;
    55.  
    56.         //Sending to all connected clients
    57.         NetworkServer.SendToAll(chatMessage,tMsg);
    58.     }
    59.  
    60.     //Server Function
    61.     private void ConnectRequest(NetworkMessage netMsg){
    62.         Debug.Log("User Connected from IP: "+netMsg.conn.address+", ID: "+netMsg.conn.connectionId);
    63.     }
    64.  
    65.     private void DisconnectRequest(NetworkMessage netMsg){
    66.         Debug.Log("Client Disconnected from IP: "+netMsg.conn.address+", ID: "+netMsg.conn.connectionId);
    67.     }
    68.  
    69.     public class NetMessage : MessageBase{
    70.         public string name;
    71.         public int id;
    72.         public string message;
    73.     }
    74. }
    75.  
    Client Code...
    Code (csharp):
    1.  
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.Networking;
    5. using UnityEngine.UI;
    6.  
    7. public class Client_Controller : MonoBehaviour {
    8.     string hostIP;
    9.     int hostPort;
    10.     bool clientStarted;
    11.  
    12.     NetworkClient netClient;
    13.     public NetworkManager netManager;
    14.     private const short chatMessage = 131;
    15.  
    16.    // Use this for initialization
    17.    void Start () {
    18.         if(!netManager){
    19.             //Grab the NetworkManager componenet
    20.             netManager = GetComponent<NetworkManager>();
    21.             Debug.Log("Getting NetManager...");
    22.         }
    23.  
    24.         Application.runInBackground = true;
    25.         DontDestroyOnLoad(transform.gameObject);
    26.  
    27.         Debug.Log("Finished start procedures...");
    28.    }
    29.  
    30.     public void RunClient(){
    31.         if(!clientStarted){
    32.             //Start Client and connect to server port
    33.             clientStarted = true;
    34.             netClient = new NetworkClient();
    35.  
    36.             netManager.networkAddress = "192.168.11.101";
    37.             netManager.networkPort = 7777;
    38.             netClient = netManager.StartClient();
    39.        
    40.            netClient.RegisterHandler(chatMessage,ReceiveMessage);
    41.             netClient.RegisterHandler(MsgType.Connect,OnConnected);
    42.             netClient.RegisterHandler(MsgType.Disconnect,DisconnectRequest);
    43.  
    44.             Debug.Log("Finished starting client...");
    45.         }
    46.     }
    47.  
    48.     public void ReceiveMessage(NetworkMessage netMsg){
    49.         //reading message
    50.         NetMessage tMsg = new NetMessage();
    51.         var tempMsg = netMsg.ReadMessage<NetMessage>();
    52.         tMsg.name = tempMsg.name;
    53.         tMsg.id = tempMsg.id;
    54.         tMsg.message = tempMsg.message;
    55.  
    56.        Debug.Log(tMsg.name+": "+tMsg.message);
    57.     }
    58.  
    59.     //Client Function
    60.     private void OnConnected(NetworkMessage netMsg){
    61.        Debug.Log("Connected to server at IP: "+hostIP+", Port: "+hostPort);
    62.     }
    63.  
    64.     private void DisconnectRequest(NetworkMessage netMsg){
    65.         Debug.Log("Client Disconnected from IP: "+netMsg.conn.address+", ID: "+netMsg.conn.connectionId);
    66.     }
    67.  
    68.     public class NetMessage : MessageBase{
    69.         public string name;
    70.         public int id;
    71.         public string message;
    72.     }
    73.  
    74.    void Update () {
    75.             //Start client
    76.            if(!clientStarted){
    77.                  RunClient();
    78.             }
    79.         }
    80.    }
    81. }
    82.  
    This is as bare bones as I could get it. You would need to expand to the scenes by adding text boxes to show user input or messages received.

    Basically, I will be using a version of this and expanding on it for future MP projects.
     
    Last edited: Dec 9, 2017
    linojon and megabrobro like this.
  21. megabrobro

    megabrobro

    Joined:
    Jul 8, 2017
    Posts:
    70

    THANK YOU VERY MUCH!! I have not yet worked through your code so I cannot yet say it has helped me (yet!) , but I defintely think making my own netmanager HUD will help me understand more about the network manager in total.

    ONE THING: I have noticed straight off the bat (just by skimreading the code) that your lines:
    netManager.networkAddress = "192.168.11.101";
    netManager.networkPort = 7777;

    Them lines seem to input the address and port directly to the network manager -- but how would this make it so that the user didnt have to input the IP/port (and also forward the port)?? what if the user was on IP 192.168.0.10 and port was 7778?


    Also, where are 'ButHostTxt' and 'hostID' declared? I get error "..does not exist in current context"
     
    Last edited: Dec 4, 2017
  22. JWLewis777

    JWLewis777

    Joined:
    May 17, 2015
    Posts:
    51
    Sorry, I chopped up my code a bit to put it here to make it as small as possible.
    I updated the server code above to show the host button, host button text and hostID.

    I hard coded the host IP in my script. Whatever IP you put here is what the client will try to connect to. You can use any port you want, just be careful you don't put a port number that is already in use. You just need to be sure its the same port number you set in the server code.

    By putting the IP address and port in the script, the user doesn't change them. Whatever ip and port is defined in the script is what the client program will try to connect to.

    Good luck!
    :)
     
    megabrobro likes this.
  23. megabrobro

    megabrobro

    Joined:
    Jul 8, 2017
    Posts:
    70
    Excellent , thank you . That was how i understood it. Its not quite what I was originally after, but an yway to get an online game functioning is what i was needing. I'm now working on some other stuff to learn, but soon will go back to the multiplayer games i started and will use your code. Thanks again
     
  24. Paden

    Paden

    Joined:
    Sep 13, 2013
    Posts:
    12
    Hey!

    I'm very new to network programming with Unity and have a few questions regarding your approach. I managed to get it working (have a server and clients connecting to said server), however there doesn't seem to be a callback that is successfully called when a client chooses to disconnect from the server (via netClient.Disconnect();). I thought that DisconnectRequest in ClientController would be called, but it doesn't seem to be (if I'm the client at least).

    I'm also wondering if there is an alternative to hard-coding the IP address you want to connect to, like some sort of way to scan for open servers on your network?

    I was trying to use the built in tools but I want to have more control as I'm not really creating a typical "multiplayer game."

    Thanks!
     
  25. jose-araujo

    jose-araujo

    Joined:
    Nov 17, 2016
    Posts:
    21
    Hi @JWLewis777, I was trying to use a bit of your code in my application and for some reason, I get an error saying that the NetworkManager does not have a definition of networkAdress, networkPort, neither the StartClient(). I defined the network manager in the same way as you did, and also have enabled the UnityEngine.Networking. Any idea what could be going wrong?

    UPDATE: Found the problem... I had defined a "NetworkManager" class in another script inside the same project which screwed up things...
     
    Last edited: Mar 6, 2018
  26. jose-araujo

    jose-araujo

    Joined:
    Nov 17, 2016
    Posts:
    21
    Hi @JWLewis777, I attached the server script to a game object and created the network manager game object and attached the "network manager" component that one can find in the network list. When I run it, I get the output "NullReferenceException: object reference not set to an instance of an object" when I call any "netManager.XYZ" step. I added the network manager game object as the "netManager" in the server script game object but I get the same output error. Any ideas of what I could be doing wrong?