How can I trigger OnPlayerConnected while using NetworkManager Unity?

≯℡__Kan透↙ 提交于 2019-12-11 06:14:24

问题


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 ?

Here is my code:

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);
    }
}

回答1:


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);
    }
}

not

public class MultiPlayerOyunKontrol : NetworkBehaviour
{

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

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.

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");
}


来源:https://stackoverflow.com/questions/43676173/how-can-i-trigger-onplayerconnected-while-using-networkmanager-unity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!