It can be hard to find information on the in-built unity networking - here is a script from my canceled multiplayer game.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class NetworkManager : MonoBehaviour {
public float connectionMaxTimeout = 10f;
float currentTimeOut = 0f;
bool connectionFailed = false;
string connectionError = "";
public GameObject playerPrefab;
public GameObject myGO;
private const string typeName = "anythinghere";
private const string gameName = "RoomName";
private HostData[] hostList;
int state = 0;
string serverName = "";
string serverPassword = "";
string joiningPassword = "";
HostData serverToJoin;
bool optionsOpen = false;
public static bool singlePlayer = true;
public static int playerCount = 0;
List<Message> messages = new List<Message>();
void Awake() {
DontDestroyOnLoad (gameObject);
}
private void StartServer()
{
if ( serverPassword != "" ) {
Network.incomingPassword = serverPassword;
}
Network.InitializeServer(4, 25000, true);
MasterServer.RegisterHost(typeName, serverName);
}
void OnServerInitialized()
{
Network.isMessageQueueRunning = false;
LoadLevel (1);
}
void Update() {
if ( Input.GetKeyDown(KeyCode.G)) {
PostMessage (false, "JHDECGW", "HAHAHA!");
}
if ( Input.GetKeyDown(KeyCode.Escape)) {
if ( optionsOpen ) {
optionsOpen = false;
}
else {
optionsOpen = true;
}
}
}
void OnGUI() {
int mm = 1;
foreach(Message m in messages) {
GUI.Label(new Rect(10, Screen.height - (20 + 20 * mm), 800, 20),m.playerName + "" + m.message);
mm++;
}
if (!Network.isClient && !Network.isServer) {
if ( Network.peerType != NetworkPeerType.Connecting ) {
if ( !connectionFailed ) {
currentTimeOut = 0f;
if ( state == 0 ) {
GUI.Box(new Rect(270, 10, Screen.width - 280, Screen.height - 20), "");
if (GUI.Button(new Rect(10, 10, 250, 100), "Start Server")) {
state = 1;
}
if (GUI.Button(new Rect(10, 120, 250, 100), "Refresh Hosts")) {
RefreshHostList();
}
if (hostList != null) {
for (int i = 0; i < hostList.Length; i++) {
string name = hostList*.gameName;*
_ if ( hostList*.passwordProtected ) { name += " |Password Protected|"; }_
_ if (GUI.Button(new Rect(280, 20 + (110 * i), Screen.width - 300, 20), name)) {
if ( hostList.passwordProtected ) {
state = 2;
serverToJoin = hostList;
}
else {
JoinServer(hostList);
}
}
}
}
}
if ( state == 1 ) {
GUI.Box(new Rect(10, 10, 250, 200), “Server Creation”);
GUI.Label(new Rect(20,38,100,20), “Server Name:”);
serverName = GUI.TextField(new Rect(120, 40, 120, 20), serverName);
GUI.Label(new Rect(20,58,100,20), “Server Pass:”);
serverPassword = GUI.TextField(new Rect(120, 60, 120, 20), serverPassword);
if (GUI.Button(new Rect(90, 85, 100, 25), “Create!”)) {
state = 0;
StartServer();
}
if (GUI.Button(new Rect(90, 115, 100, 25), “Back”)) {
serverName = “”;
serverPassword = “”;
state = 0;
}
}
if ( state == 2) {
GUI.Box(new Rect(10, 10, 150, 100), “Input Password”);
joiningPassword = GUI.TextField(new Rect(10, 50, 100, 20), joiningPassword);
if (GUI.Button(new Rect(75, 50, 50, 25), “Join!”)) {
JoinServer(serverToJoin);
}
if (GUI.Button(new Rect(105, 50, 50, 25), “Back”)) {
joiningPassword = “”;
state = 0;
}
}
}
else {
PostMessage(false, “”, connectionError);
connectionFailed = false;
}
}
else {
if ( Network.peerType == NetworkPeerType.Connecting ) {
currentTimeOut += Time.deltaTime;
if (currentTimeOut <= connectionMaxTimeout) {
GUI.Box(new Rect(Screen.width/2-100, Screen.height/2-10, 200, 20), “Connecting…”);
}
else {
GUI.Box(new Rect(Screen.width/2-100, Screen.height/2-10, 200, 20), “Failed to connect.”);
if (currentTimeOut >= connectionMaxTimeout+2) {
Network.Disconnect();
}
}
}
}
}
if ( Network.isClient || Network.isServer ) {
if ( optionsOpen ) {
GUI.Window(0, new Rect (Screen.width / 2 - 400, Screen.height / 2 - 300, 800, 600), DoOptionsWindow, “Options”);
}
}
}*_
* void DoOptionsWindow(int windowID) {*
* GUI.Label (new Rect(10, 20, 200, 20), "Light Quality: ");*
* GUI.Label (new Rect(10, 43, 300, 20), "Anti-Aliasing: ");*
* GUI.Label (new Rect (10, 72, 300, 20), "Animation Quality: ");*
* QualitySettings.pixelLightCount = System.Convert.ToInt32(GUI.HorizontalSlider (new Rect(200, 25, 300, 20), QualitySettings.pixelLightCount, 2, 10));*
* if (QualitySettings.antiAliasing == 0 ){GUI.color=Color.green;}else{GUI.color=Color.red;}if (GUI.Button (new Rect (200, 40, 24, 24), “0x”)) { QualitySettings.antiAliasing = 0; }*
* if (QualitySettings.antiAliasing == 2 ){GUI.color=Color.green;}else{GUI.color=Color.red;}if (GUI.Button (new Rect (230, 40, 24, 24), “2x”)) { QualitySettings.antiAliasing = 2; }*
* if (QualitySettings.antiAliasing == 4 ){GUI.color=Color.green;}else{GUI.color=Color.red;}if (GUI.Button (new Rect (260, 40, 24, 24), “4x”)) { QualitySettings.antiAliasing = 4; }*
* if (QualitySettings.antiAliasing == 8 ){GUI.color=Color.green;}else{GUI.color=Color.red;}if (GUI.Button (new Rect (290, 40, 24, 24), “8x”)) { QualitySettings.antiAliasing = 8; }*
* if (QualitySettings.blendWeights == BlendWeights.OneBone ){GUI.color=Color.green;}else{GUI.color=Color.red;}if (GUI.Button (new Rect (200, 70, 40, 24), “Low”)) { QualitySettings.blendWeights = BlendWeights.OneBone; }*
* if (QualitySettings.blendWeights == BlendWeights.TwoBones ){GUI.color=Color.green;}else{GUI.color=Color.red;}if (GUI.Button (new Rect (250, 70, 40, 24), “Med”)) { QualitySettings.blendWeights = BlendWeights.TwoBones; }*
* if (QualitySettings.blendWeights == BlendWeights.FourBones ){GUI.color=Color.green;}else{GUI.color=Color.red;}if (GUI.Button (new Rect (300, 70, 40, 24), “High”)) { QualitySettings.blendWeights = BlendWeights.FourBones; }*
* }*
* void OnFailedToConnect(NetworkConnectionError error) {*
* if (error == NetworkConnectionError.NATPunchthroughFailed) {*
* connectionFailed = true;*
* connectionError = “Connection Failed (NAT Punchthrough failed).”;*
* }*
* if (error == NetworkConnectionError.InvalidPassword) {*
* connectionFailed = true;*
* connectionError = “Connection Failed (Invalid password).”;*
* }*
* if (error == NetworkConnectionError.ConnectionBanned) {*
* connectionFailed = true;*
* connectionError = “Connection Failed (Banned).”;*
* }*
* if (error == NetworkConnectionError.EmptyConnectTarget) {*
* connectionFailed = true;*
* connectionError = “Connection Failed (Invaild target).”;*
* }*
* if (error == NetworkConnectionError.NoError) {*
* connectionFailed = true;*
* connectionError = “Connection Failed (Unknown error).”;*
* }*
* if (error == NetworkConnectionError.TooManyConnectedPlayers) {*
* connectionFailed = true;*
* connectionError = “Connection Failed (Server full).”;*
* }*
* }*
* private void RefreshHostList() {*
* MasterServer.RequestHostList(typeName);*
* }*
* void OnMasterServerEvent(MasterServerEvent msEvent) {*
* if (msEvent == MasterServerEvent.HostListReceived)*
* hostList = MasterServer.PollHostList();*
* }*
* private void JoinServer(HostData hostData) {*
* Network.Connect(hostData, joiningPassword);*
* }*
* void OnConnectedToServer() {*
* UpdatePlayerCount();*
* LoadLevel (1);*
* }*
* void LoadLevel(int i) {*
* Network.isMessageQueueRunning = false;*
* Application.LoadLevel (i);*
* }*
* void OnLevelWasLoaded() {*
* if ( Application.loadedLevel == 1 ) {*
* Network.isMessageQueueRunning = true;*
* myGO = Network.Instantiate(playerPrefab, new Vector3(0f, 2.5f, 0f), Quaternion.identity, 0) as GameObject;*
* myGO.transform.Find(“Main Camera”).GetComponent ().enabled = true;*
* myGO.transform.Find(“Main Camera”).GetComponent ().enabled = true;*
* myGO.GetComponent ().enabled = true;*
* GetComponent().CreateMyGUI();*
* }*
* }*
* void OnPlayerDisconnected(NetworkPlayer player) {*
* Debug.Log("Clean up after player " + player);*
* Network.RemoveRPCs(player);*
* Network.DestroyPlayerObjects(player);*
* Debug.Log (“Player Disconnected”);*
* UpdatePlayerCount();*
* }*
* void OnPlayerConnected(NetworkPlayer player) {*
* Debug.Log (“Player Connected”);*
* UpdatePlayerCount();*
* }*
* void UpdatePlayerCount() {*
* playerCount = Network.connections.Length;*
* if ( playerCount < 1 ) {*
* singlePlayer = true;*
* }*
* else {*
* singlePlayer = false;*
* }*
* Debug.Log (playerCount.ToString ());*
* }*
* [System.Serializable]*
* public class Message {*
* public bool hasPlayer = false;*
* public string playerName = “”;*
* public string message = “”;*
* }*
* [RPC] void PostMessage(bool hasPlayer, string playerName, string message) {*
* Message msg = new Message();*
* msg.hasPlayer = hasPlayer;*
* msg.playerName = playerName;*
* msg.message = message;*
* messages.Add (msg);*
* }*
}
This is for a general server (for FPS and stuff), I don’t know how to set up a master server.
It’s not perfect, and has some debug elements in it. This script creates a GUI, with the ability to host and join servers, once you join or host a server, your player gameobject(which you have to set up in the inspector) will be spawned in scene index 1. This is untested by itself, so it may require some patch work to get working.