0
点赞
收藏
分享

微信扫一扫

unity Mirror网络同步

我们直接来剖析,上干货

在github上的主页代码,稍微修改了下:

using System.Collections;
using System.Collections.Generic;
using Mirror;
using UnityEngine;

public class Player : NetworkBehaviour
{
    // Synced automatically //自动同步
    [SyncVar] public int health = 100;
    
    // Lists, Dictionaries, Sets too  列表、字典、集也是如此
   // SyncList<Item> inventory = new SyncList<Item>();
    
    // Server/Client-only code  仅限 ServerClient 的代码
    [Server] void LevelUp() {} //会阻止客户端运行此方法
    [Client] void Animate() {} //会阻止服务端运行此方法
    
    void Update()
    {
        // isServer/isClient for runtime checks  isServerisClient 用于运行时检查
        if (isServer) Heal();  //通过这个标签判断是否是服务端
        if (isClient) Move();  //通过这个标签判断是否是客户端
    }

    private void Move()
    {
        throw new System.NotImplementedException();
    }

    private void Heal()
    {
        throw new System.NotImplementedException();
    }

    // Zero overhead remote calls   零开销远程呼叫
    [Command]   void CmdUseItem(int slot) {} // Client to Server  客户端到服务器
    [ClientRpc] void RpcRespawn() {}         // Server to all Clients  服务器到所有客户端
    [TargetRpc] void Hello() {}              // Server to one Client 服务器到一个客户端
}

经过注释后大部分都已经一目了然了,但是下面这个标签是怎么回事呐?(请移步以下链接了解,我就不再赘述)

关于Unet的[Command]和[ClientRpc],[syncVar]的理解和使用-CSDN博客

总体来说,就是如果你要结合做局域网的东西,一个客户端带有服务器,其他的都是客户端,那么你的代码要嵌套着使用:Commd和ClientRpc(局域网游戏推荐)

如果你要做网络同步类型的网游,需要与服务器强连接的那种,那么你的代码要嵌套着使用:Commd和TargetRpc(不推荐)

这样达到的目的在于一套代码多处可以重复使用(虽然大多数用不着这么做,也不推荐,如果你要做这种游戏,反而不推荐使用这个插件,建议自己根据:skywind3000/kcp: :zap: KCP - A Fast and Reliable ARQ Protocol (github.com))

进行自主封装(推荐)

然后你想要正常使用这个插件,你需要建一个网络对象的空物体,在上面挂载三个脚本:

一般空物体叫:NetworkManager

三个脚本:

NetworkManager、NetworkManagerHUD、KcpTransport

建议加上这个:NetworkPingDisplay(一看这名就知道是干啥的)

举报

相关推荐

0 条评论