UIFader.cs 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. using UnityEngine;
  2. using UnityEngine.UI;
  3. public class UIFader : MonoBehaviour
  4. {
  5. public float flashSpeed = 0.5f; // 闪烁速度
  6. public float minAlpha = 0f; // 最低透明度
  7. public float maxAlpha = 1f; // 最高透明度
  8. private Image[] childImages;
  9. private bool flashing = false;
  10. void OnEnable()
  11. {
  12. // 只获取子物体上的 Image
  13. childImages = GetComponentsInChildren<Image>(true);
  14. childImages = System.Array.FindAll(childImages, img => img.gameObject != this.gameObject);
  15. flashing = true;
  16. }
  17. void OnDisable()
  18. {
  19. flashing = false;
  20. // 恢复透明度为 1
  21. if (childImages != null)
  22. {
  23. foreach (var img in childImages)
  24. {
  25. if (img != null)
  26. {
  27. Color c = img.color;
  28. c.a = 1f;
  29. img.color = c;
  30. }
  31. }
  32. }
  33. }
  34. void Update()
  35. {
  36. if (!flashing || childImages == null) return;
  37. float alpha = Mathf.Lerp(minAlpha, maxAlpha, (Mathf.Sin(Time.time * flashSpeed) + 1f) / 2f);
  38. foreach (var img in childImages)
  39. {
  40. if (img != null)
  41. {
  42. Color c = img.color;
  43. c.a = alpha;
  44. img.color = c;
  45. }
  46. }
  47. }
  48. }