Skip to content

Instantly share code, notes, and snippets.

@grimmdev
Created November 2, 2014 07:14
Show Gist options
  • Save grimmdev/cc3ae3102a8b7f08cad0 to your computer and use it in GitHub Desktop.
Save grimmdev/cc3ae3102a8b7f08cad0 to your computer and use it in GitHub Desktop.
Simple Server/Connect
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class MultiplayerServer: MonoBehaviour
{
// Server Settings
public int maxPlayers = 11;
// Player Settings
public GameObject playerGO;
public Vector3 spawnPoint;
// used to Randomize Player Position
private Vector3 SpawnRandom ()
{
Vector3 v = new Vector3 (Random.Range (-10, 10), 0, Random.Range (-10, 10));
return v;
}
void Awake ()
{
MasterServer.ClearHostList();
MasterServer.RequestHostList("ARM_UNI");
}
void OnGUI ()
{
if(Network.peerType == NetworkPeerType.Disconnected)
{
if(GUILayout.Button("QUICK PLAY"))
{
List<HostData> serverList = new List<HostData>();
foreach(HostData serverData in MasterServer.PollHostList())
{//declare serverdata as our Hostdata
if(serverData.connectedPlayers < serverData.playerLimit)
{
serverList.Add(serverData);
//Add our host game data to our serverlist
}
}
if(serverList.Count > 0)
{
Network.Connect(serverList[0]);
}
else
{
StartServer();
}
}
}
else
{
if(GUILayout.Button("DISCONNECT"))
{
Network.Disconnect();
}
}
}
void StartServer ()
{
Network.InitializeServer(maxPlayers, Random.Range(1000, 5000), !Network.HavePublicAddress());
MasterServer.RegisterHost("ARM_UNI", "Armed_Unity", "");
Network.Instantiate(playerGO, SpawnRandom(), transform.rotation, 0);
}
void OnConnectedToServer ()
{
Network.Instantiate(playerGO, SpawnRandom(), transform.rotation, 0);
}
void OnPlayerConnected(NetworkPlayer player) {
}
void OnPlayerDisconnected ( NetworkPlayer player )
{
Network.RemoveRPCs(player);
Network.DestroyPlayerObjects(player);
}
void OnDisconnectedFromServer ()
{
Application.LoadLevel(Application.loadedLevel);
}
void OnApplicationQuit() {
Network.Disconnect ();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment