| 开发多人同步项目时,物体Transform信息同步分为两种: Player(客户端自主控制,服务器广播,其他客户端刷新)NPC(自身带有AI逻辑,服务器广播其Transform、Animator属性,所有客户端刷新)可接力操作物体(如Aclient 将一个物体交给BClient)
 前两种情况,网上教程很多,不再赘述。 第三种情况,没有找到相关介绍,而且官网介绍也有一个坑。 Network Transform - Mirror https://mirror-networking.gitbook.io/docs/components/network-transform这里说到  
 By default, Network Transform is server-authoritative unless you check the box for Client Authority. Client Authority applies to player objects as well as non-player objects that have been specifically assigned to a client, but only for this component. With this enabled, position changes are send from the client to the server. 实践中:场景创建Cube添加NetworkTransform(自动添加NetworkIdentity)勾选ClientAuthority ?打包测试后发现,客户端和服务器都自能各自移动,却不同步位置。 解决方案:仍然勾选该选项,并且在当前操作client请求权限 注意Command请求只能在player上,所以该脚本应该放挂在player上 using Mirror;
using UnityEngine;
public class AuthorityAndOwnerShip : NetworkBehaviour
{
    private GameObject prefab;
    void Update() 
    {
        bool isplayerDead = false;
        if (isplayerDead && base.hasAuthority)
        {
            CmdRequestRespawn();
        }
        RequestOwnerShipOnClick();
    }
    [Command]
    private void CmdRequestRespawn() 
    {
        NetworkServer.Spawn(prefab,GetComponent<NetworkIdentity>().connectionToClient);
    }
    private void RequestOwnerShipOnClick() 
    {
        if (!base.hasAuthority)
        {
            return;
        }
        if (!Input.GetMouseButton(2))
        {
            return;
        }
        RaycastHit hit;
        if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition),out hit,100))
        {
            NetworkIdentity id = hit.collider.GetComponent<NetworkIdentity>();
            if (id != null && !id.hasAuthority)
            {
                CmdRequestAuthority(id);
            }
        }
    }
    [Command]
    private void CmdRequestAuthority(NetworkIdentity id)
    {
        id.RemoveClientAuthority();
        id.AssignClientAuthority(base.connectionToClient);
    }
}
 为了验证该效果,在Cube 上挂载一个验证脚本 using Mirror;
using UnityEngine;
public class ChangeColorOnAuthority : NetworkBehaviour
{
    public override void OnStartAuthority()
    {
        base.OnStartAuthority();
        GetComponent<MeshRenderer>().material.color = Color.blue;
    }
    public override void OnStopAuthority()
    {
        base.OnStopAuthority();
        GetComponent<MeshRenderer>().material.color = Color.white;
    }
    void Update() 
    {
        if (Input.GetMouseButton(1))
        {
            transform.Rotate(Vector3.down, Input.GetAxis("Mouse X"));
            transform.Rotate(Vector3.left, -Input.GetAxis("Mouse Y"));
        }
    }
}
 链接后,在client上用鼠标中键点击cube、接收到权限后会变成蓝色。此时点击鼠标右键并滑动。旋转角度就会同步回服务器了。 效果视频: |