Blipples

FloatingHealthBar

May 9th, 2024
18
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.95 KB | None | 0 0
  1. using FishNet.Object;
  2. using FishNet.Object.Synchronizing;
  3. using System;
  4. using System.Collections;
  5. using System.Collections.Generic;
  6. using UnityEngine;
  7. using UnityEngine.Events;
  8. using UnityEngine.UI;
  9.  
  10. public class FloatingHealthBar : NetworkBehaviour
  11. {
  12. private readonly SyncVar<float> healthValue = new SyncVar<float>();
  13. Observer<Stat> totalStatsHealthValue;
  14.  
  15. private StatManager statManager;
  16. private Slider healthBar;
  17.  
  18. public override void OnStartClient()
  19. {
  20. if (!base.IsOwner)
  21. {
  22. GetComponent<FloatingHealthBar>().enabled = false;
  23. }
  24.  
  25. statManager = transform.root.GetComponent<StatManager>();
  26. healthBar = GetComponent<Slider>();
  27.  
  28. StartCoroutine(ConfigureListener());
  29.  
  30. healthValue.OnChange += HealthValue_OnChange;
  31.  
  32. CalculateHealthPercentage();
  33. }
  34.  
  35. public override void OnStopClient()
  36. {
  37. healthValue.OnChange -= HealthValue_OnChange;
  38. }
  39.  
  40. private IEnumerator ConfigureListener()
  41. {
  42. while(statManager.CharacterTotalStats == null)
  43. {
  44. yield return null;
  45. }
  46.  
  47. totalStatsHealthValue = statManager.CharacterTotalStats.statsDictionary[StatType.Primary][PrimaryStat.HP];
  48. totalStatsHealthValue.AddListener(CalculateHealthPercentage);
  49. }
  50.  
  51. private void CalculateHealthPercentage()
  52. {
  53. float value = (float)statManager.CharacterTotalStats.statsDictionary[StatType.Primary][PrimaryStat.HP].Value.StatValue /
  54. (float)statManager.CharacterTotalStats.statsDictionary[StatType.Primary][PrimaryStat.MaxHP].Value.StatValue;
  55.  
  56. SetHealthValueServer(value);
  57. }
  58.  
  59. [ServerRpc]
  60. private void SetHealthValueServer(float healthPercentage)
  61. {
  62. healthValue.Value = healthPercentage;
  63. }
  64.  
  65. private void HealthValue_OnChange(float prev, float next, bool asServer)
  66. {
  67. healthBar.value = healthValue.Value;
  68. }
  69. }
  70.  
Advertisement
Add Comment
Please, Sign In to add comment