using UnityEngine; using UnityEngine.UI; using System.Collections; public class ScreenHit : MonoBehaviour { public static ScreenHit Instance { get; private set; } // Singleton instance private Image hitImage; private Coroutine fadeCoroutine; public float fadeDuration = 0.3f; // Time to fade in and out private void Awake() { if (Instance == null) { Instance = this; } else { Destroy(gameObject); return; } hitImage = GetComponent(); if (hitImage == null) { Debug.LogError("[ScreenHit] No Image component found! Make sure it's attached to a UI Image."); } // Start fully transparent Color color = hitImage.color; color.a = 0; hitImage.color = color; } public void ShowHitEffect() { if (fadeCoroutine != null) { StopCoroutine(fadeCoroutine); } fadeCoroutine = StartCoroutine(FadeEffect()); } private IEnumerator FadeEffect() { float halfDuration = fadeDuration / 2f; Color color = hitImage.color; // Fade in float elapsed = 0f; while (elapsed < halfDuration) { color.a = Mathf.Lerp(0, 1, elapsed / halfDuration); hitImage.color = color; elapsed += Time.deltaTime; yield return null; } // Fade out elapsed = 0f; while (elapsed < halfDuration) { color.a = Mathf.Lerp(1, 0, elapsed / halfDuration); hitImage.color = color; elapsed += Time.deltaTime; yield return null; } color.a = 0; // Fully transparent hitImage.color = color; } }