CockHpComp.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. using System;
  2. using UnityEngine;
  3. using UnityEngine.UI;
  4. namespace Comp
  5. {
  6. public class CockHpComp : MonoBehaviour
  7. {
  8. // 血量条组件
  9. private Image _backgroundImage, _foregroundImage;
  10. private int _maxHp, _curHp;
  11. public int reduceHp; // 需要扣除的Hp
  12. public int MaxHp
  13. {
  14. set
  15. {
  16. _maxHp = value;
  17. _curHp = _maxHp;
  18. }
  19. }
  20. private void ReduceCurHp(int hp)
  21. {
  22. _curHp -= hp;
  23. var hpPercent = (float)_curHp / _maxHp;
  24. if (hpPercent > 0.5f)
  25. {
  26. _foregroundImage.color = Color.green;
  27. }
  28. else if (hpPercent is >= 0.25f and <= 0.5f)
  29. {
  30. _foregroundImage.color = Color.yellow;
  31. }
  32. else
  33. {
  34. _foregroundImage.color = Color.red;
  35. }
  36. var backgroundSize = _backgroundImage.rectTransform.sizeDelta;
  37. var foregroundSize = _foregroundImage.rectTransform.sizeDelta;
  38. var newForegroundWidth = backgroundSize.x * hpPercent;
  39. _foregroundImage.rectTransform.sizeDelta = new Vector2(newForegroundWidth, foregroundSize.y);
  40. }
  41. private void Start()
  42. {
  43. // 获取血条的填充图片
  44. var images = GetComponentsInChildren<Image>();
  45. foreach (var image in images)
  46. {
  47. if (image.name == "Background")
  48. {
  49. _backgroundImage = image;
  50. }
  51. if (image.name == "Foreground")
  52. {
  53. _foregroundImage = image;
  54. }
  55. }
  56. }
  57. private void Update()
  58. {
  59. if (reduceHp != 0)
  60. {
  61. ReduceCurHp(reduceHp);
  62. reduceHp = 0;
  63. }
  64. }
  65. }
  66. }