70 lines
1.6 KiB
C#
70 lines
1.6 KiB
C#
|
|
using UnityEngine;
|
||
|
|
using System.Collections;
|
||
|
|
|
||
|
|
public class FlashBehaviour : MonoBehaviour
|
||
|
|
{
|
||
|
|
public GameObject square; // Assign in inspector or find in Start
|
||
|
|
public float flashInDuration = 0.05f;
|
||
|
|
public float flashOutDuration = 0.2f;
|
||
|
|
|
||
|
|
private Color squareColor;
|
||
|
|
private Coroutine flashCoroutine;
|
||
|
|
private SpriteRenderer spriteRenderer;
|
||
|
|
|
||
|
|
void Start()
|
||
|
|
{
|
||
|
|
|
||
|
|
if (square == null)
|
||
|
|
square = transform.Find("Square")?.gameObject;
|
||
|
|
|
||
|
|
if (square != null)
|
||
|
|
spriteRenderer = square.GetComponent<SpriteRenderer>();
|
||
|
|
|
||
|
|
if (spriteRenderer != null)
|
||
|
|
{
|
||
|
|
squareColor = spriteRenderer.color;
|
||
|
|
squareColor.a = 0;
|
||
|
|
}
|
||
|
|
|
||
|
|
}
|
||
|
|
|
||
|
|
public void TriggerFlash()
|
||
|
|
{
|
||
|
|
if (flashCoroutine != null)
|
||
|
|
StopCoroutine(flashCoroutine);
|
||
|
|
flashCoroutine = StartCoroutine(FlashRoutine());
|
||
|
|
}
|
||
|
|
|
||
|
|
private IEnumerator FlashRoutine()
|
||
|
|
{
|
||
|
|
// Fade in
|
||
|
|
float t = 0;
|
||
|
|
while (t < flashInDuration)
|
||
|
|
{
|
||
|
|
t += Time.deltaTime;
|
||
|
|
SetAlpha(Mathf.Lerp(0, 1, t / flashInDuration));
|
||
|
|
yield return null;
|
||
|
|
}
|
||
|
|
SetAlpha(1);
|
||
|
|
|
||
|
|
// Fade out
|
||
|
|
t = 0;
|
||
|
|
while (t < flashOutDuration)
|
||
|
|
{
|
||
|
|
t += Time.deltaTime;
|
||
|
|
SetAlpha(Mathf.Lerp(1, 0, t / flashOutDuration));
|
||
|
|
yield return null;
|
||
|
|
}
|
||
|
|
SetAlpha(0);
|
||
|
|
}
|
||
|
|
|
||
|
|
private void SetAlpha(float alpha)
|
||
|
|
{
|
||
|
|
if (spriteRenderer != null)
|
||
|
|
{
|
||
|
|
squareColor.a = alpha;
|
||
|
|
spriteRenderer.color = squareColor;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|