我是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);
}
}
答案 0 :(得分:0)
我假设你想要的是:
在任何时候都会在客户端上调用函数Flip()
。
=>他的本地Sprite已更改,您希望通过服务器将其同步到其他客户端。
如果是这种情况,您会错误地使用Command
和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);
}