SyncVar 不工作 Unity Networking

SyncVar not working Unity Networking

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

  1. 我用命令函数改变了变量
  2. 我正确地添加了 syncvar 属性和钩子
  3. 客户端可以更新服务器上的变量,但服务器不更新客户端上的变量

这是我的脚本:

玩家射击脚本:

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 () {

}
}

以下是一些屏幕截图:

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

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