Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using FishNet.Object;
- using FishNet.Object.Synchronizing;
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- using UnityEngine.Events;
- using UnityEngine.UI;
- public class FloatingHealthBar : NetworkBehaviour
- {
- private readonly SyncVar<float> healthValue = new SyncVar<float>();
- Observer<Stat> totalStatsHealthValue;
- private StatManager statManager;
- private Slider healthBar;
- public override void OnStartClient()
- {
- if (!base.IsOwner)
- {
- GetComponent<FloatingHealthBar>().enabled = false;
- }
- statManager = transform.root.GetComponent<StatManager>();
- healthBar = GetComponent<Slider>();
- StartCoroutine(ConfigureListener());
- healthValue.OnChange += HealthValue_OnChange;
- CalculateHealthPercentage();
- }
- public override void OnStopClient()
- {
- healthValue.OnChange -= HealthValue_OnChange;
- }
- private IEnumerator ConfigureListener()
- {
- while(statManager.CharacterTotalStats == null)
- {
- yield return null;
- }
- totalStatsHealthValue = statManager.CharacterTotalStats.statsDictionary[StatType.Primary][PrimaryStat.HP];
- totalStatsHealthValue.AddListener(CalculateHealthPercentage);
- }
- private void CalculateHealthPercentage()
- {
- float value = (float)statManager.CharacterTotalStats.statsDictionary[StatType.Primary][PrimaryStat.HP].Value.StatValue /
- (float)statManager.CharacterTotalStats.statsDictionary[StatType.Primary][PrimaryStat.MaxHP].Value.StatValue;
- SetHealthValueServer(value);
- }
- [ServerRpc]
- private void SetHealthValueServer(float healthPercentage)
- {
- healthValue.Value = healthPercentage;
- }
- private void HealthValue_OnChange(float prev, float next, bool asServer)
- {
- healthBar.value = healthValue.Value;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment