Starting my app for 'host' networking mode in unity

392 views Asked by At

Been going through some tutorials and the unity documentation to learn how to start up a networking instance as a 'host' but all that I've been able to find is how to initialize a system as a client or a server. I've attached code below that will startup in either server or client mode, but how do I go about initializing for host mode?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;

public class NetworkManager : MonoBehaviour {

    public static NetworkManager Instance = null; // create singleton
    public bool host;
    private int hostPort = 7777;
    private string hostIP = "192.168.1.160";
    string networkConnections;

    private void Awake()
    {
        InitNetworkManager();
    }

    private void Update()
    {
        if (Network.isServer)
        {
            networkConnections = NetworkServer.connections.Count.ToString();
        }
    }

    void InitNetworkManager()
    {
        if (Instance == null)
            Instance = this;
        else if (Instance != null)
            Destroy(gameObject);

        if (host && !Network.isServer)
        {
            // setup server
            LaunchServer();
            return;
        }
        else if (!host && !Network.isClient) 
        {
            // setup client
            LaunchClient();
            return;
        }
    }

    void LaunchServer()
    {
        Network.InitializeServer(32, hostPort, true);
        Debug.Log("Server Launched");
    }

    void LaunchClient()
    {
        Network.Connect(hostIP, hostPort);
        Debug.Log("Client Launched");
    }
}
1

There are 1 answers

0
Muhammad Faizan Khan On BEST ANSWER

Actually when You are running a player you are a normal player. Neither you are server nor you are client. So you this code does not make any sense.

if (host && !Network.isServer)
        {
            // setup server
            LaunchServer();
            return;
        }
        else if (!host && !Network.isClient) 
        {
            // setup client
            LaunchClient();
            return;
        }

isServer - true if the object is on a server (or host) and has been spawned.

isClient - true if the object is on a client, and was created by the server.

Instead you should provide three option to user

  1. Server
  2. Host (Server + Client)
  3. Client

Either provide these option using GUI button or using any option. You can use Network Manager to launch three modes of the application.

  1. StartHost: This starts a network "host" - a server and client in the same application.
  2. StartClient: This starts a network client. It uses the networkAddress and networkPort properties as the address to connect to.
  3. StartServer: This starts a new server.