本文介绍了使用 NetworkManager Unity 时如何触发 OnPlayerConnected?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 UNet 和 NetworkManager 组件.我试图在玩家连接到服务器时对我说我已连接".我必须连载它.我正在使用 NetworkBehaviour,我认为这可能会导致失败.但是我怎样才能序列化它?

I am using UNet and NetworkManager component. I am trying to when the player connected to server just say to me 'I am connected'. I must serialize that. I am using NetworkBehaviour, I think this may lead to failure. But how can I serialize that ?

这是我的代码:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using UnityEngine.Networking;
public class MultiPlayerOyunKontrol : NetworkBehaviour
{

    void OnPlayerConnected(NetworkPlayer player)
    {
        Debug.Log("Player  baglandi"+this.transform.name);
    }
}

推荐答案

OnPlayerConnected 函数甚至不是 UNet API 的一部分.它是 Unity 传统网络 API 的一部分.这是应该如何使用的:

The OnPlayerConnected function is not even part of UNet API. It's part of Unity's legacy network API. This is how should have been be used:

public class MultiPlayerOyunKontrol : MonoBehaviour
{
    void OnPlayerConnected(NetworkPlayer player)
    {
        Debug.Log("Player  baglandi"+this.transform.name);
    }
}

不是

public class MultiPlayerOyunKontrol : NetworkBehaviour
{

    void OnPlayerConnected(NetworkPlayer player)
    {
        Debug.Log("Player  baglandi"+this.transform.name);
    }
}

基本上,OnPlayerConnectedNetworkBehaviour 无关,因此除非您使用旧的 Unity 网络 API,否则它不会工作.

Basically, OnPlayerConnected has nothing to do with NetworkBehaviour so it wouldn't work unless you are using the old Unity network API which you're not.

以下是查看客户端何时与 UNet 连接或断开连接的正确方法:

Below is a proper way to see when client is connected or disconnected with UNet:

void Start()
{
    NetworkServer.Listen(9000);
    NetworkServer.RegisterHandler(MsgType.Connect, OnConnected);
    NetworkServer.RegisterHandler(MsgType.Disconnect, OnDisconnected);
    NetworkServer.RegisterHandler(MsgType.Error, OnError);
}

public void OnConnected(NetworkMessage netMsg)
{
    Debug.Log("Client Connected");
}

public void OnDisconnected(NetworkMessage netMsg)
{
    Debug.Log("Disconnected");
}

public void OnError(NetworkMessage netMsg)
{
    Debug.Log("Error while connecting");
}

这篇关于使用 NetworkManager Unity 时如何触发 OnPlayerConnected?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 22:38