首页 > 解决方案 > 非玩家对象权限转移问题

问题描述

我正在制作多人游戏,我想让玩家与非玩家对象进行交互(任何玩家都可以更改其变换)。当我与第一个加入的玩家(或主持的人)互动时,它正在工作,但如果我尝试与另一个玩家(第二个加入的人)互动,对象会回到第一个玩家离开的位置他在。

所以我尝试的是转移非玩家对象的权限,但我遇到了以下错误。任何人都遇到同样的问题或知道任何其他方式来完成上述任务?我正在使用以下代码来更改权限:

    [Command]
    void Cmd_AssignLocalAuthority(GameObject obj)
    {
        print("shifting authority successfully");
        NetworkInstanceId nIns = obj.GetComponent<NetworkIdentity>().netId;
        GameObject client = NetworkServer.FindLocalObject(nIns);
        NetworkIdentity ni = client.GetComponent<NetworkIdentity>();
        ni.AssignClientAuthority(connectionToClient);
    }

    [Command]
    void Cmd_RemoveLocalAuthority(GameObject obj)
    {
        print("reverting authority successfully");
        NetworkInstanceId nIns = obj.GetComponent<NetworkIdentity>().netId;
        GameObject client = NetworkServer.FindLocalObject(nIns);
        NetworkIdentity ni = client.GetComponent<NetworkIdentity>();
        ni.RemoveClientAuthority(ni.clientAuthorityOwner);
    }

我得到的错误是这个

在此处输入图像描述

标签: unity3dmultiplayerunity3d-unetunity-networking

解决方案


您需要知道应该从播放器对象而不是对象本身调用更改,因为它没有权限。

要设置权限,您应该执行以下操作:

    [Command]
    public void CmdSetAuth(NetworkInstanceId objectId, NetworkIdentity player)
    {
        GameObject iObject = NetworkServer.FindLocalObject(objectId);
        NetworkIdentity networkIdentity = iObject.GetComponent<NetworkIdentity>();

        //Checks if anyone else has authority and removes it and lastly gives the authority to the player who interacts with object
        NetworkConnection otherOwner = networkIdentity.clientAuthorityOwner;
        if (otherOwner == player.connectionToClient)
        {
            return;
        }
        else
        {
            if (otherOwner != null)
            {
                networkIdentity.RemoveClientAuthority(otherOwner);
            }
            networkIdentity.AssignClientAuthority(player.connectionToClient);
        }

        networkIdentity.AssignClientAuthority(player.connectionToClient);
    }

推荐阅读