[SyncVar]属性在我的游戏中对我不起作用。我已经确定:
以下是我的脚本:
玩家射击脚本:
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 () {
}
}
以下是一些屏幕截图:
答案 0 :(得分:1)
由于您正在使用函数挂钩SyncVar,您需要手动传递变量(并执行您希望对新值执行的其他操作,例如检查hp&lt; = 0)。
void UpdateUI(int hp){
currentHealth = hp;
healthBar.value = currentHealth;
}