unity3d 为什么健康量表在网络游戏中不起作用?

m1m5dgzv  于 2023-01-31  发布在  其他
关注(0)|答案(1)|浏览(102)

我想做一个在线游戏中的玩家的生命值刻度。它会产卵,但不会减少。我使用镜像。我尝试使用SynhVar,但它没有给予我任何东西。请帮助我,我不知道该怎么做。

using UnityEngine;
using UnityEngine.UI;
using Mirror;

public class Player : NetworkBehaviour
{
    private Rigidbody2D rb;
    public float speed;
    private Vector2 input;

    public GameObject prefabIndicators;
    public Image bar;
     [SyncVar]public float fill;

    private void Start() 
    {
       rb = GetComponent<Rigidbody2D>();
       CmdSpawn();
       fill = 1f;
    }

    private void Update() 
    {
        if(!isLocalPlayer) return;

        input = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));

        bar.fillAmount = fill;
        fill -= Time.deltaTime * 0.1f;
    }

    private void FixedUpdate()
    {
        rb.MovePosition(rb.position + input * speed / 100);

    }

    [Command]
    private void CmdSpawn() 
    {
        GameObject prefab = Instantiate(prefabIndicators, transform.position, Quaternion.identity);
        NetworkServer.Spawn(prefab);

    }
}
hlswsv35

hlswsv351#

如前所述,仅当您是本地玩家时才分配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);
}

更进一步说(可能是错误的),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);
    }
}

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

相关问题