UNET Let first client start as host automatically

Hi,

What I would like:

  • First client starts the game. It sees that there is no server available, so it starts the game as host.
  • All other clients connect to the existing host
  • If the host leaves the game, another client becomes the host automatically.

What I’ve tried:

	void Update()
	{
		if (NetworkServer.active == false)
		{
			Debug.Log("NetworkServer inactive.");
			if (NetworkClient.active == false)
			{
				Debug.Log("NetworkServer and NetworkClient inactive. Starting as host.");
				//m_Manager.StartHost();
			}
		}
		else
		{
			Debug.Log("NetworkServer active.");
			if (NetworkClient.active == false)
			{
				Debug.Log("NetworkServer active and client inactive. Connecting as client.");
				//m_Manager.StartClient();
			}
		}
	}

So far it’s telling me that the server is inactive on both clients, although one of them has started a local host. Manually connecting and all of those things work fine. Is “NetworkServer.active” only true for the local instance? Do I need to somehow test the connection to find out if the server exists on the network instead?

Is this approach viable at least for debugging and testing during development? Our project will have its own dedicated server later, but we don’t have access to it until a few months.

Thanks!

@Xarbrough

Hello, did you solve this problem afterwards?

I was just struggling on the same problem so I came across your post via Google.

Per my test, “NetworkServer.xxx” will only work on the server, so your code will not work as expected.

Now I have an idea that is to use NetworkDiscovery. The process would be like this.

Whenever a user clicks the “Join Game” button, start to listen for server broadcast message. (call NetworkDiscovery.StartAsClient ()).

If there is a host already, “OnReceivedBroadcast” function will be automatically called, call StartClient in this function.

If there is no host, (you can set up a timeout, e.g. 3 seconds) it means after 3 seconds call StartHost and start to send broadcast message as a host.