How can I trigger OnPlayerConnected while using Ne

2019-08-01 13:37发布

问题:

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