【问题标题】:Unet not sync a float value between client-server , server-clientUnet 不同步客户端-服务器、服务器-客户端之间的浮点值
【发布时间】:2019-09-03 14:01:14
【问题描述】:

我尝试在服务器-客户端之间同步浮点值。

在服务器屏幕上有老板 HpBar 脚本在场景中设置了 MAXHP 值。

玩家预制件拥有自己的boss HP UI和localhp脚本,它们将从服务器中的HpBar脚本获取当前boss HP值。

当用户按下攻击按钮时,它会将伤害值发送到 HpBar 脚本,然后它应该更新到播放器预制件。但它不会同步在一起。谢谢

图片在这里 https://imgur.com/a/KrYtC3T

localPlayerHPBAR 脚本:

public class localHpBar : NetworkBehaviour
{

    public HpBar serverHp;
    public float localhpPoint;
    public Image localhpBar;

    // Start is called before the first frame update
    void Start()
    {
        serverHp = GameObject.FindObjectOfType<HpBar>();
        //Get OBJ of serverHP
    }

    public void sendDamage(float dmg)
    {
        serverHp.TakeDamage(dmg); //SendDamageToserver
    }

    // Update is called once per frame
    void Update()
    { 
        //get HP point from server
        localhpPoint = serverHp.sum;
        localhpBar.fillAmount = localhpPoint;
    }
}

服务器 HpBar

public class HpBar : NetworkBehaviour
{
    public Image HP;
    public float MaxHP;
    float currentHP;
    public float localhp;
    [SyncVar] public float sum;

    void Start()
    { 
        //set CURRENT HP
        currentHP = MaxHP;
    }

    [ClientRpc]
    void rpcDamage(float dmg)
    {       
        sum = currentHP / MaxHP;
        HP.fillAmount = sum;
    }

    public void TakeDamage(float dmg)
    {

        //recieve DamageFrom client
        currentHP = currentHP - dmg;
        rpcDamage(currentHP);
    }
}

【问题讨论】:

    标签: unity3d unity-networking


    【解决方案1】:

    注意[SyncVar] 只是同步服务器 &rightarrow;客户。

    从不在另一个方向。在客户端更改此值不会影响服务器或其他客户端。

    您正在使用[ClientRpc] 更改sum[ClientRpc]服务器 调用,但在所有客户端上执行。你甚至不能作为客户调用它。


    您应该做的是将TakeDamage 方法设置为[Command],以便客户端调用它,但只在 服务器 上执行,然后您可以在其中更改同步值,例如

    // This is called by clients but executed on the server
    [Command]
    public void CmdTakeDamage(float dmg)
    {
        currentHP -= dmg;
    
        sum = currentHP / MaxHP;
    
        // actually pass on the new sum
        rpcDamage(sum);
    }
    
    // This is called ONLY by the server but executed on all clients
    [ClientRpc]
    // also make sure the prefix is capital Rpc otherwise it might not work
    void RpcDamage(float newSum)
    {
        // if you set sum here then you should simply remove the 
        // [SyncVar] since you already sync it "manually"
        // I would actually do this since it is not guaranteed that the syncvar
        // transfers its new value before this method is executed
        // on the other hand syncvar is additionally synchronized when connecting a new client
        // so you might have to do it "manually"
        sum = newSum;
        HP.fillAmount = sum;
    }
    

    【讨论】:

    • 谢谢。当我在主机上按下攻击 btn 时,代码工作和值同步。但在客户端它不会更新值。谢谢
    猜你喜欢
    • 1970-01-01
    • 2014-05-25
    • 1970-01-01
    • 2013-11-16
    • 1970-01-01
    • 2012-09-26
    • 2011-02-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多