【问题标题】:How to send a message or event into Server Unity3D?如何将消息或事件发送到服务器 Unity3D?
【发布时间】:2018-07-23 17:50:26
【问题描述】:

我正在学习 Unity 中的网络。我对如何从客户端向服务器发送消息或事件感到困惑。我已经有了这些脚本,可以成功地将我的客户端连接到服务器。

这是我的服务器脚本:

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

public class ServerNetwork : MonoBehaviour {

    void Start()
    {
        SetupServer();
    }

    // Create a server and listen on a port
    public void SetupServer()
    {

        NetworkServer.Listen(4444);
        NetworkServer.RegisterHandler(MsgType.Connect, OnClientConnected);
        Debug.Log("Server is running");
    }

    void OnClientConnected(NetworkMessage netMsg)
    {
        Debug.Log("Client connected");
        Debug.Log(netMsg.msgType);
    }
}

这是我的客户端脚本:

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

public class ClientNetwork : MonoBehaviour {

    NetworkClient myClient;
    public bool isClientConnected = false;

    void Start()
    {
        SetupClient();
    }

    // Create a client and connect to the server port
    public void SetupClient()
    {
        myClient = new NetworkClient();
        myClient.RegisterHandler(MsgType.Connect, OnConnected);
        myClient.Connect("127.0.0.1", 4444);
        isClientConnected = true;
    }

    // client function
    public void OnConnected(NetworkMessage netMsg)
    {
        Debug.Log("Connected to server");
    }
}

服务器脚本附加到 ServerScene 上的“NetworkManager”对象

客户端脚本附加到 ClientScene 上的“NetworkManager”对象

我已经单独构建了 ClientScene 作为客户端运行,并在编辑器中运行 ServerScene

使用这些脚本,我已经可以将客户端连接到服务器。从这里,我如何从客户端到服务器进行通信?

这里的目的是每秒从客户端向服务器发送实时分数。

谢谢

【问题讨论】:

    标签: unity3d networking


    【解决方案1】:

    你必须使用[SyncVars] 属性。简而言之,它的作用是将变量从客户端同步到服务器。这是来自Unity3d 文档的一个简单示例。

    [SyncVar]
    int health;
    
    public void TakeDamage(int amount)
    {
        if (!isServer)
            return;
    
        health -= amount;
    }
    

    另一种方法是使用 Unity3D 的自定义 WebSocket 实现。 GitHub里面有几个非常不错的,也请看文档Unity3d

    【讨论】:

    • 我试过SyncVar,但是说调用函数时没有NetworkIdentity。我已经更新了这个问题。我为两个脚本使用不同的场景或对象
    • @AdityoSetyonugroho 在这种情况下,您应该在客户端使用 Send() 或 SendBytes() 方法。它们也很容易配置。我希望这会有所帮助。
    猜你喜欢
    • 1970-01-01
    • 2014-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-06
    相关资源
    最近更新 更多