【问题标题】:Why does the health scale not work in an online game?为什么健康秤在网络游戏中不起作用?
【发布时间】:2023-02-01 01:16:57
【问题描述】:

我想为玩家制作一个健康秤。无论其他玩家如何,我都需要玩家的规模自行缩小。它减少了,但它只在第二个客户端连接之前有效,然后第一个值被重置并且它不再为第一个或第二个减少。例如,下面的代码也不起作用。

using UnityEngine;
using UnityEngine.UI;
using Mirror;

public class Player : NetworkBehaviour
{
    public Image bar;
    [SyncVar] public float fill;

    private void Start() 
    {
        if(!isLocalPlayer) return;
        fill = 1f;
    }

    [Command]
    public void CmdUpdateFill(float newFill)
    {
        fill = newFill;
    }

    private void Update() 
    {
        if(!isLocalPlayer) return;
        bar.fillAmount = fill;
        fill -= Time.deltaTime * 0.1f;
        CmdUpdateFill(fill);
    }
}

【问题讨论】:

  • 所以我看到你在哪里产卵……但是你根本不使用它所以产卵的东西应该怎么发生?
  • 但我使用填充变量。你能告诉我如何正确地做吗?
  • 您有时在本地使用 fillAmount,这在其他远程客户端上无处使用...
  • 以及如何去做?..

标签: c# unity3d


【解决方案1】:

如前所述,仅当您是本地玩家时才分配fill

但是在所有其他播放器上,您实际上从未对其进行过任何操作。

你可以试试

private void Start() 
{
   // Also want to check here and skip on other players
   if(!isLocalPlayer) return;

   rb = GetComponent<Rigidbody2D>();
   CmdSpawn();
   fill = 1f;
}

private void Update() 
{
    if(isLocalPlayer)
    {
        input = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));

        fill -= Time.deltaTime * 0.1f;
    }

    // You want to do this part also on the other clients
    bar.fillAmount = fill;       
}

private void FixedUpdate()
{
    // Also want to skip this on other players
    if(!isLocalPlayer) return;

    rb.MovePosition(rb.position + input * speed / 100);
}

进一步 afaik(可能是错误的)SyncVar 仅从服务器同步到客户端!所以在这里你实际上需要通过服务器传递它而不是直接设置它,例如

[Command]
private void CmdSetFill(float value)
{
    // Is now synced down to clients
    fill = value;
}

private void Update ()
{
    if(isLocalPlayer)
    {
        input = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));

        CmdSetFill(fill - Time.deltaTime * 0.1f);
    }
}

请注意,仍然在每一帧调用一个命令并不是网络带宽方面的最佳方法。

【讨论】:

  • 变量减少,但条形图没有减少。 :(
猜你喜欢
  • 2018-12-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-15
相关资源
最近更新 更多