using System; using UnityEngine; using UnityEngine.UI; namespace Comp { public class CockHpComp : MonoBehaviour { // 血量条组件 private Image _backgroundImage, _foregroundImage; private int _maxHp, _curHp; public int reduceHp; // 需要扣除的Hp public int MaxHp { set { _maxHp = value; _curHp = _maxHp; } } private void ReduceCurHp(int hp) { _curHp -= hp; var hpPercent = (float)_curHp / _maxHp; if (hpPercent > 0.5f) { _foregroundImage.color = Color.green; } else if (hpPercent is >= 0.25f and <= 0.5f) { _foregroundImage.color = Color.yellow; } else { _foregroundImage.color = Color.red; } var backgroundSize = _backgroundImage.rectTransform.sizeDelta; var foregroundSize = _foregroundImage.rectTransform.sizeDelta; var newForegroundWidth = backgroundSize.x * hpPercent; _foregroundImage.rectTransform.sizeDelta = new Vector2(newForegroundWidth, foregroundSize.y); } private void Start() { // 获取血条的填充图片 var images = GetComponentsInChildren(); foreach (var image in images) { if (image.name == "Background") { _backgroundImage = image; } if (image.name == "Foreground") { _foregroundImage = image; } } } private void Update() { if (reduceHp != 0) { ReduceCurHp(reduceHp); reduceHp = 0; } } } }