I'm trying to avoid manually determining if the current instance of a running unity game is the host or client. Is there a way to detect existing games, and if there are join them, if there aren't start a host?
Note that players are not aware of networked content, so I cannot expect them to start an own host or pick an existing one to connect to.
I tried it with the NetworkDiscovery
component as follows:
public class TestPlayerSetup : NetworkDiscovery {
private float timeToWait = 1f;
private float timeWaited = 0f;
private bool hostDiscovered = false;
void Start () {
NetworkManager.singleton.networkAddress = "localhost";
NetworkManager.singleton.networkPort = 7777;
Initialize ();
StartAsClient ();
}
void Update() {
if (timeWaited < timeToWait) {
timeWaited += Time.deltaTime;
return;
}
if (!hostDiscovered) {
NetworkServer.Reset ();
NetworkManager.singleton.StartHost ();
StartAsServer ();
hostDiscovered = true;
}
}
public override void OnReceivedBroadcast(string fromAddress, string data){
Debug.Log ("received broadcast");
NetworkManager.singleton.StartClient();
hostDiscovered = true;
setPlayerColor ();
}
}
But it seems you can't start a NetworkDiscovery
server after having started a client.