将 Sprite 渲染器的翻转与 unet 同步

Sync Sprite renderer's flip with unet

我是 Unity 的新手。我正在开发一款简单的多人游戏。

我面临的问题是当我们按下左右箭头键时,我无法同步精灵渲染器的翻转状态。

下面是我试过的代码。

[SerializeField] 
private SpriteRenderer spriteRenderer;

[Command]
void CmdProvideFlipStateToServer(bool state)
{
    spriteRenderer.flipX = state;
}

[ClientRpc]
void RpcSendFlipState(bool state)
{
    CmdProvideFlipStateToServer(state);
}

private void Flip()
{
    facingRight = !facingRight;
    if(isClient){
        spriteRenderer.flipX = !facingRight;
    }
    if(isLocalPlayer){
        RpcSendFlipState(spriteRenderer.flipX);
    }
}

我假设你想要的是:

随时在客户端上调用函数 Flip()

=> 他的本地 Sprite 已更改,您想通过服务器将其同步到其他客户端。


如果是这种情况,您使用 CommandClientRpc 的方式有误:

  • Command:在Client端调用,但只在Server端执行
  • ClientRpc:在服务器上调用但仅在(所有)客户端上执行

=> 你的脚本应该看起来像

[SerializeField] 
private SpriteRenderer spriteRenderer;

// invoked by clients but executed on the server only
[Command]
void CmdProvideFlipStateToServer(bool state)
{
    // make the change local on the server
    spriteRenderer.flipX = state;

    // forward the change also to all clients
    RpcSendFlipState(state)
}

// invoked by the server only but executed on ALL clients
[ClientRpc]
void RpcSendFlipState(bool state)
{
    // skip this function on the LocalPlayer 
    // because he is the one who originally invoked this
    if(isLocalPlayer) return;

    //make the change local on all clients
    spriteRenderer.flipX = state;
}

// Client makes sure this function is only executed on clients
// If called on the server it will throw an warning
// https://docs.unity3d.com/ScriptReference/Networking.ClientAttribute.html
[Client]
private void Flip()
{
    //Only go on for the LocalPlayer
    if(!isLocalPlayer) return;

    // make the change local on this client
    facingRight = !facingRight;
    spriteRenderer.flipX = !facingRight;

    // invoke the change on the Server as you already named the function
    CmdProvideFlipStateToServer(spriteRenderer.flipX);
}