using System.Collections;
using UnityEngine;
using BaseGames.Feedback;
namespace BaseGames.VFX
{
///
/// 受伤闪白效果控制器。
/// 通过 MaterialPropertyBlock 修改 SpriteRenderer 材质的 _FlashAmount 参数(0~1);
/// 对应 Shader 需暴露 _FlashColor 与 _FlashAmount 两个属性。
/// 调用 Flash() 触发一次闪白动画(Coroutine 实现,不依赖 UniTask)。
///
public class HurtFlashController : MonoBehaviour
{
[SerializeField] private SpriteRenderer _renderer;
[SerializeField] private FeedbackConfigSO _config;
private static readonly int FlashColorID = Shader.PropertyToID("_FlashColor");
private static readonly int FlashAmountID = Shader.PropertyToID("_FlashAmount");
private MaterialPropertyBlock _block;
private Coroutine _flashCoroutine;
private WaitForSeconds _waitForFlash;
private void Awake()
{
Debug.Assert(_config != null, "[HurtFlashController] _config 未赋值,请在 Inspector 中指定 FeedbackConfigSO。", this);
if (_renderer == null)
_renderer = GetComponent();
_block = new MaterialPropertyBlock();
if (_config != null)
_waitForFlash = new WaitForSeconds(_config.HurtFlashDuration);
}
/// 触发一次闪白动画。若上一次闪白未结束则重置计时器。
public void Flash()
{
if (_flashCoroutine != null)
StopCoroutine(_flashCoroutine);
_flashCoroutine = StartCoroutine(FlashCoroutine());
}
private IEnumerator FlashCoroutine()
{
SetFlash(1f);
yield return _waitForFlash ?? new WaitForSeconds(_config.HurtFlashDuration);
SetFlash(0f);
_flashCoroutine = null;
}
private void SetFlash(float amount)
{
_renderer.GetPropertyBlock(_block);
_block.SetColor(FlashColorID, _config.HurtFlashColor);
_block.SetFloat(FlashAmountID, amount);
_renderer.SetPropertyBlock(_block);
}
}
}