Home > Software engineering >  Unity multiplayer
Unity multiplayer

Time:12-07

Down Below is the code for connection approval. As shown in the image I want to turn off the Home menu GameObject(The object containing the canvas) the moment we become host or client. But In the update loop the control do not go to else statement if I am the client but it does go when I am the host. Why is that ?

[This is the image][1]

using Unity.Netcode;
using UnityEngine;
using TMPro;

public class ConnectionApproval : NetworkBehaviour
{
    public TMP_InputField ThePassword;
    public GameObject HomeMenu;

    private void Update()
    {
        if (!NetworkManager.Singleton.IsServer || !NetworkManager.Singleton.IsClient)
        {
            HomeMenu.SetActive(true);
        }
        else
        {
            Debug.Log("I am "   NetworkManager.Singleton.IsServer.ToString()   " "   NetworkManager.Singleton.IsClient.ToString());
            HomeMenu.SetActive(false);
        }

    }

    private void ApprovalCheck(byte[] connectionData_, ulong connectionId_, NetworkManager.ConnectionApprovedDelegate callback)
    {
        bool IsApproved = Encoding.ASCII.GetString(connectionData_) == ThePassword.text;
        callback(true, null, IsApproved, new Vector3(Random.Range(-3f, 3f), 1f, 0f), Quaternion.identity);
    }
    
    public void Host()
    {
        NetworkManager.Singleton.ConnectionApprovalCallback  = ApprovalCheck;
        NetworkManager.Singleton.StartHost();
    }


    public void Client()
    {
        NetworkManager.Singleton.NetworkConfig.ConnectionData = Encoding.ASCII.GetBytes(ThePassword.text);
        NetworkManager.Singleton.StartClient();
    }

}```


  [1]: https://i.stack.imgur.com/ipWR8.png

CodePudding user response:

NetworkManager.Singleton.IsServer should be replaced with NetworkManager.Singleton.IsHost and || must be replaced by && because we cannot be both host and remote client at the same time.

  • Related