Files
zeling_v2/Assets/Scripts/VFX/HurtFlashController.cs
2026-05-12 15:34:08 +08:00

57 lines
2.0 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.Collections;
using UnityEngine;
using BaseGames.Feedback;
namespace BaseGames.VFX
{
/// <summary>
/// 受伤闪白效果控制器。
/// 通过 MaterialPropertyBlock 修改 SpriteRenderer 材质的 _FlashAmount 参数0~1
/// 对应 Shader 需暴露 _FlashColor 与 _FlashAmount 两个属性。
/// 调用 Flash() 触发一次闪白动画Coroutine 实现,不依赖 UniTask
/// </summary>
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 void Awake()
{
Debug.Assert(_config != null, "[HurtFlashController] _config 未赋值,请在 Inspector 中指定 FeedbackConfigSO。", this);
if (_renderer == null)
_renderer = GetComponent<SpriteRenderer>();
_block = new MaterialPropertyBlock();
}
/// <summary>触发一次闪白动画。若上一次闪白未结束则重置计时器。</summary>
public void Flash()
{
if (_flashCoroutine != null)
StopCoroutine(_flashCoroutine);
_flashCoroutine = StartCoroutine(FlashCoroutine());
}
private IEnumerator FlashCoroutine()
{
SetFlash(1f);
yield return 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);
}
}
}