【问题标题】:SyncVar not working Unity NetworkingSyncVar 不工作 Unity Networking
【发布时间】:2016-05-26 02:23:52
【问题描述】:

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

}
}

以下是一些屏幕截图:

【问题讨论】:

    标签: c# networking unity3d network-programming unity5


    【解决方案1】:

    由于您将 SyncVar 与函数挂钩,因此您需要手动传递变量(并对新值执行您希望执行的其他操作,例如检查 hp

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

    【讨论】:

      猜你喜欢
      • 2019-01-15
      • 2018-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-20
      • 1970-01-01
      • 2016-10-14
      • 1970-01-01
      相关资源
      最近更新 更多