SyncVar无法正常运行Unity Networking

时间:2016-05-26 02:23:53

标签: c# networking unity3d network-programming unity5

[SyncVar]属性在我的游戏中对我不起作用。我已经确定:

  1. 我使用命令功能
  2. 更改了变量
  3. 我正确添加了syncvar属性和hook
  4. 客户端可以更新服务器上的变量,但服务器不会更新客户端上的变量
  5. 以下是我的脚本:

    玩家射击脚本:

    using UnityEngine;
    
    using System.Collections;
    
    using UnityEngine.Networking;
    
    public class PlayerShoot : NetworkBehaviour {
    
    public GameObject shootPosition;
    
    public float shootRange = 100;
    public float shootRate = 0.2f;
    float nextCheck;
    
    public int damage = 10;
    
    // Use this for initialization
    void Start () {
    
    }
    
    void DetectShooting(){
        if (Time.time > nextCheck && Input.GetMouseButton(0)) {
            nextCheck = Time.time + shootRate;
            CmdShoot ();
        }
    
    }
    
    [Command]
    void CmdShoot(){
        RaycastHit hit;
        Ray bulletDirection = new Ray (shootPosition.transform.position, transform.forward * shootRange);
        Debug.DrawRay (shootPosition.transform.position, transform.forward * shootRange, Color.blue, 10.0f);
        if (Physics.Raycast (bulletDirection, out hit, 100)) {
            print (hit.transform.name);
    
            if (hit.transform.CompareTag ("Player")) {
                hit.transform.GetComponent<PlayerHealth> ().DeductHealth (damage);
    
            }
    
        }
    }
    
    // Update is called once per frame
    void Update () {
        print (isLocalPlayer);
        if (isLocalPlayer)
        DetectShooting ();
    }
    }
    

    播放器健康脚本:

    using UnityEngine;
    using System.Collections;
    using UnityEngine.UI;
    using UnityEngine.Networking;
    
     public class PlayerHealth : NetworkBehaviour {
    
    
    public static int maxHealth = 100;
    
    [SyncVar (hook ="UpdateUI")]
    public int currentHealth = maxHealth;
    
    public Slider healthBar;
    
    void UpdateUI(int hp){
        healthBar.value = currentHealth;
    }
    
    public void DeductHealth(int damage){
        if (isServer)
        currentHealth -= damage;
    
    }
    
    // Use this for initialization
    void Start () {
        //InvokeRepeating ("DeductHealth", 0, 2);
        SetInitialReferences ();
    }
    
    void SetInitialReferences(){
    
    
    }
    
    // Update is called once per frame
    void Update () {
    
    }
    }
    

    以下是一些屏幕截图:

    Client Screen Shot After shooting the host

    Host Screen Shot After being shot

1 个答案:

答案 0 :(得分:1)

由于您正在使用函数挂钩SyncVar,您需要手动传递变量(并执行您希望对新值执行的其他操作,例如检查hp&lt; = 0)。

void UpdateUI(int hp){
    currentHealth = hp;
    healthBar.value = currentHealth;
}