簡體   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