using UnityEngine; using UnityEngine.UI; using System.Collections; /// /// UI提示 /// public class ImageTips : MonoBehaviour { private Image image; // UI Image组件 public float fadeDuration = 1.0f; // 每次淡入淡出的持续时间 private RectTransform selfRect; public Vector2 sizeOffset = new Vector2(100, 100); public void ShowTips(RectTransform target) { gameObject.SetActive(true); selfRect = GetComponent(); image = GetComponent(); selfRect.SetParent(target); selfRect.anchorMin = Vector2.zero; selfRect.anchorMax = new Vector2(1, 1); selfRect.offsetMax = Vector2.zero; selfRect.offsetMin = Vector2.zero; //selfRect.sizeDelta = target.sizeDelta + sizeOffset; if (gameObject.activeSelf) StartCoroutine(FlashRoutine()); } public void HideTips() { transform.parent = null; StopCoroutine(FlashRoutine()); gameObject.SetActive(false); } private IEnumerator FlashRoutine() { while (true) { yield return StartCoroutine(Fade(1.0f, fadeDuration)); yield return StartCoroutine(Fade(0.0f, fadeDuration)); } } private IEnumerator Fade(float targetAlpha, float duration) { float startAlpha = image.color.a; float elapsed = 0.0f; while (elapsed < duration) { elapsed += Time.deltaTime; float newAlpha = Mathf.Lerp(startAlpha, targetAlpha, elapsed / duration); Color color = image.color; color.a = newAlpha; image.color = color; yield return null; } // 确保最终值准确 Color finalColor = image.color; finalColor.a = targetAlpha; image.color = finalColor; } }