- Home /
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");
}
}
}
Your answer
Follow this Question
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