Search Unity

Server Side IP and Port Setting Example

Discussion in 'Multiplayer' started by Deleted User, Oct 20, 2017.

  1. Deleted User

    Deleted User

    Guest

    Hi Guys,

    New to Unity and I've currently written the below c# script to handle getting the input of an IP and Port on the command line and then starting my host only server using this details.

    I'm sharing both for re-use and to ask for feedback on if this is a good way to do this or weather there is a cleaner/different way?

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.Networking;
    5. using UnityEngine.UI;
    6.  
    7. public class ServerCode : NetworkBehaviour {
    8.  
    9.     string[] args = System.Environment.GetCommandLineArgs();
    10.     string serverPort = "7777";
    11.     string serverIP = "127.0.0.1";
    12.  
    13.     // Use this for initialization
    14.     void Start()
    15.     {
    16.         for (int i = 0; i < args.Length; i++)
    17.         {
    18.             if (args[i] == "-port")
    19.             {
    20.                 serverPort = args[i + 1];
    21.             }
    22.             if (args[i] == "-ip")
    23.             {
    24.                 serverIP = args[i + 1];
    25.             }
    26.         }
    27.          
    28.         if (System.Array.IndexOf (args, "-server") >= 0) {
    29.  
    30.             NetworkManager.singleton.networkPort = int.Parse(serverPort);
    31.             NetworkManager.singleton.serverBindAddress = serverIP;
    32.             NetworkManager.singleton.serverBindToIP = true;
    33.             NetworkManager.singleton.StartServer ();
    34.         } else {
    35.             //Debug.Log("You didn't start a server this time!");
    36.             //Application.Quit ();
    37.         }
    38.          
    39.     }
    40.      
    41. }
    Currently the way I launch this is:

    Code (Boo):
    1. GameProject.exe -batchmode -nographics -server -ip 192.168.0.2 -port 1234
     
  2. xVergilx

    xVergilx

    Joined:
    Dec 22, 2014
    Posts:
    3,296
    If it's works and it's good enough - then it's ok.

    One thing though - don't use == comparison for strings, use .Equals instead;
    Also, hard coded values can be put into consts, or statics in a separate file, but that's just my preferences.
     
    Deleted User likes this.