Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by WillBeDone · Sep 19, 2013 at 07:31 PM · networkingmaster server

How to create Networking in Unity?

Hello everyone.

I am currently trying to build a prototype for a game a I am making and I am trying to get the Networking up and running but I am struggling to do so. I was hoping someone could help me. The thing I am struggling to do right now is connect to a Master Server. I have tried using Unity's, however I cannot connect to it. Then I tried downloading their Master Server code and trying it on my own computer, and I still cannot connect. I have looked up a lot of different tutorials and still have not found the answer. If anyone can help, it would be greatly appreciated. Also, I would like to try and get a basic prototype without using an plugins such as Photon. I will look into those later. Here is the code I have so far:

     public class NetworkingScript : MonoBehaviour
 {
     public int ButtonWidthOffset;
     public int ButtonHeightOffset;
     
     public int WindowHorizontalOffset = 0;
     public float WindowWidthModifier = 0.2f;
     
     public int WindowVerticalOffset = 0;
     public float WindowHeightModifier = 0.2f;
     
     private string TestStatus = "Testing network connection capabilities.";
     private string TestMessage = "Test in progress";
     private string ShouldEnableNatMessage = "";
     bool DoneTesting = false;
     bool ProbingPublicIP = false;
     int ServerPort = 9999;
     ConnectionTesterStatus ConnectionTestResult = ConnectionTesterStatus.Undetermined;
     
     bool UseNat = false;
     
     private string ServerName = "", MaxPlayers = "0", PortNumber = "10101";
     private Rect windowRect = new Rect(0, 0, 400, 400);
     private List<HostData> hostData = new List<HostData>();
     
     // Use this for initialization
     void Awake ()
     {
         // MasterServer.ipAddress = my IP address
     }
     
     void OnGUI()
     {    
         if(Network.peerType == NetworkPeerType.Disconnected)
         {
             GUILayout.Label("Server Name");
             ServerName = GUILayout.TextField(ServerName);
             
             GUILayout.Label("Port Number");
             PortNumber = GUILayout.TextField(PortNumber);
             
             GUILayout.Label("Max Player");
             MaxPlayers = GUILayout.TextField(MaxPlayers);    
             
             if(GUI.Button(new Rect(Screen.width * 0.25f + ButtonWidthOffset, Screen.height * 0.4f + ButtonHeightOffset, 100f, 50f), "Create Game"))
             {
                 try
                 {
                     Debug.Log("Server has been initiated");
                     InitializeServer(MaxPlayers, PortNumber, !Network.HavePublicAddress());
                 }
                 
                 catch(Exception)
                 {
                     Debug.Log("Please type in numbers for port and max players");    
                 }
             }
             
             if(GUI.Button(new Rect(Screen.width * 0.75f + ButtonWidthOffset, Screen.height * 0.8f + ButtonHeightOffset, 100f, 50), "Quit \"Game\""))
             {
                 Application.Quit();    
             }
             
             
             GUILayout.Window(0, new Rect(Screen.width / 2 + WindowHorizontalOffset, WindowVerticalOffset, Screen.width * WindowWidthModifier, Screen.height * WindowHeightModifier), WindowFunction, "Servers");
             
     //        GUILayout.Label("Current Status: " + TestStatus);
     //        GUILayout.Label("Test result : " + TestMessage);
     //        GUILayout.Label(ShouldEnableNatMessage);
     //        if (!DoneTesting)
     //            TestConnection();
         }
     }
     
     private void InitializeServer(string maxPlayers, string portNumber, bool useNat)
     {
         Network.InitializeSecurity();
         Network.InitializeServer(int.Parse(maxPlayers), int.Parse(portNumber), useNat);
         MasterServer.RegisterHost("PrototypingNetworking_Candlelight", ServerName, "This is for prototyping");
         Debug.Log(string.Format("The IP Address of the Unity Master Server is {0}", MasterServer.ipAddress));
     }
     
     void TestConnection()
     {
         ConnectionTestResult = Network.TestConnection();
         switch(ConnectionTestResult)
         {
             case ConnectionTesterStatus.Error:
             {
                 TestMessage = "Problem determining NAT capabilities";
                 DoneTesting = true;
                 break;
             }
                 
             case ConnectionTesterStatus.Undetermined:
             {
                 TestMessage = "Undetermined NAT capabilites";
                 DoneTesting = false;
                 break;
             }
                 
             case ConnectionTesterStatus.PublicIPPortBlocked:
             {
                 TestMessage = "Non-connectable public IP address (port " + ServerPort + " blocked), running a server is impossible.";
                 UseNat = false;
                 float timer = 0f;
                 
                 if(!ProbingPublicIP)
                 {
                     ConnectionTestResult = Network.TestConnectionNAT();
                     ProbingPublicIP = true;
                     TestStatus = "Testing if blocked public IP can be circumvented";
                     timer = Time.time + 10;
                 }
                 
                 else if(Time.time > timer)
                 {
                     ProbingPublicIP = false;
                     UseNat = true;
                     DoneTesting = true;
                 }
                 
                 break;
             }
             
             case ConnectionTesterStatus.PublicIPNoServerStarted:
             {
                 TestMessage    = "Public IP address but server not initialized, it must be started to" +
                     " check server accessability. Restart connection test when ready.";
                 break;
             }
                 
             case ConnectionTesterStatus.LimitedNATPunchthroughPortRestricted:
             {
                 TestMessage = "Limited NAT punchthrough capabilities. Cannot connect to all types" +
                     " of NAT servers. Running a server is ill advised as not everyone can connect.";
                 UseNat = true;
                 DoneTesting = true;
                 break;
             }
                 
             case ConnectionTesterStatus.LimitedNATPunchthroughSymmetric:
             {
                 TestMessage = "Limited NAT punchthrough capabilities. Cannot connect to all types" +
                     " of NAT servers. Running a server is ill advised as not everyone can connect.";
                 UseNat = true;
                 DoneTesting = true;
                 break;
             }
                 
             case ConnectionTesterStatus.NATpunchthroughAddressRestrictedCone:
             case ConnectionTesterStatus.NATpunchthroughFullCone:
             {
                 TestMessage = "NAT punchthrough capable. Can connect to all servers and receive " +
                         " connections from all clients. Enabling NAT punchthrough functionality.";
                 UseNat = true;
                 DoneTesting = true;
                 break;
             }
                 
             default:
             {
                 TestMessage = "Error in test routine, got " + ConnectionTestResult;
                 break;
             }
         }
             
         if(DoneTesting)
         {
             if(UseNat)
                 ShouldEnableNatMessage = "When start a server the NAT punchthrough feature" +
                         " should be enabled (useNat parameter)";
             else
                 ShouldEnableNatMessage = "NAT punchthrough not needed";
                 
             TestStatus = "Done Testing";
                 
         }
     }
     
     private void WindowFunction(int id)
     {
         if(GUILayout.Button("Refresh"))
         {
             MasterServer.RequestHostList("PrototypingNetworking_Candlelight");    
         }
         
         GUILayout.BeginHorizontal();
         
         GUILayout.Box("Server Name");
         
         GUILayout.EndHorizontal();
         
         if(MasterServer.PollHostList().Length != 0)
         {
             HostData[] data = MasterServer.PollHostList();
             for(int i = 0; i < data.Length; i++)
             {
                 GUILayout.BeginHorizontal();
                 GUILayout.Box(data[i].gameName);
                 if(GUILayout.Button ("Connect"))
                 {
                     Network.Connect(data[i]);    
                 }
                 
                 GUILayout.EndHorizontal();
             }
         }
         
         GUI.DragWindow(new Rect(0, 0, Screen.width, Screen.height));
     }
     
     
     
     // Messages
     
     void OnMasterServerEvent(MasterServerEvent mse)
     {
         switch(mse)
         {
             case MasterServerEvent.RegistrationFailedGameName:
             {
                 Debug.Log("The registration of the GameName has failed");    
                 break;
             }
                 
             case MasterServerEvent.RegistrationFailedGameType:
             {
                 Debug.Log("The registration of the GameType has failed");
                 break;
             }
                 
             case MasterServerEvent.RegistrationFailedNoServer:
             {
                 Debug.Log("Failed to register to a Master Server");
                 break;
             }
                 
             case MasterServerEvent.RegistrationSucceeded:
             {
                 Debug.Log("Successfully registered to the Master Server");
                 break;
             }
                 
             default:
             {
                 Debug.Log("Unknown Error has occured");    
                 break;
             }
         }
             
     }
 
     void OnFailedToConnect(NetworkConnectionError error)
     {
         Debug.Log(string.Format("Failed to connect to the Master Server. Error: {0}. Please tell Nathan! He will rescue you!", error), this.gameObject);
     }
     
     void OnConnectedToServer()
     {
         Debug.Log(string.Format("Connected to server! Waiting for other players to join. Tell Nate diggity dog that you connected!"));    
     }
     
     void OnPlayerConnected()
     {
         Debug.Log(string.Format("Connected to server! You can now start playing Propoganda!"));    
     }
     
     void OnPlayerDisconnected(NetworkPlayer disconnectedPlayer)
     {
         Debug.Log(string.Format("{0} has disconnected from the game. Cleaning up.", disconnectedPlayer));
         Network.RemoveRPCs(disconnectedPlayer);
         Network.DestroyPlayerObjects(disconnectedPlayer);
     }
     
     void OnDisconnectedFromServer(NetworkDisconnection info)
     {
         if(Network.isServer)
         {
             Debug.Log("Server has been disconnected");    
         }
         
         else
         {
             if(NetworkDisconnection.LostConnection == info)
             {
                 Debug.Log("You have lost the connection to the server");    
             }
             
             else
             {
                 Debug.Log("Successfully disconnected from the server");    
             }
         }
     }
Comment
Add comment
10 |3000 characters needed characters left characters exceeded
â–¼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

0 Replies

· Add your reply
  • Sort: 

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

15 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

The name 'Joystick' does not denote a valid type ('not found') 2 Answers

Photon Network Pong Game 0 Answers

yield return WWW; not returning 1 Answer

Network restrictive rendering 1 Answer

unity c# RPC 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges