繁体   English   中英

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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM