使用DoTween重构淡变效果
This commit is contained in:
@@ -2,6 +2,7 @@ using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
using DG.Tweening;
|
||||
|
||||
namespace OCES.Audio
|
||||
{
|
||||
@@ -106,39 +107,64 @@ namespace OCES.Audio
|
||||
{
|
||||
if (handle.Cancelled) break;
|
||||
elapsed += Time.deltaTime;
|
||||
float t = Mathf.Clamp01(elapsed / duration);
|
||||
float vol = Mathf.Lerp(fromVolume, 0f, t);
|
||||
// 为每个 source 创建 DOFade(仅创建一次)
|
||||
sources.Clear();
|
||||
handle.CollectActiveSources(sources);
|
||||
|
||||
foreach (AudioSource src in sources)
|
||||
if (src) src.volume = vol;
|
||||
{
|
||||
if (!src) continue;
|
||||
|
||||
if (DOTween.IsTweening(src))
|
||||
continue;
|
||||
|
||||
src.volume = fromVolume;
|
||||
src.DOFade(0f, duration - elapsed).SetEase(Ease.Linear);
|
||||
}
|
||||
yield return null;
|
||||
}
|
||||
|
||||
// 确保最终状态
|
||||
sources.Clear();
|
||||
handle.CollectActiveSources(sources);
|
||||
foreach (AudioSource src in sources)
|
||||
if (src) src.volume = 0f;
|
||||
|
||||
StopHandle(handle);
|
||||
}
|
||||
|
||||
IEnumerator FadeIn(ContainerPlayHandle handle, float duration)
|
||||
{
|
||||
//Debug.Log($"Fading In {duration} seconds.");
|
||||
if (handle == null || handle.Cancelled) yield break;
|
||||
|
||||
float elapsed = 0f;
|
||||
List<AudioSource> sources = new();
|
||||
float elapsed = 0f;
|
||||
|
||||
while (elapsed < duration)
|
||||
{
|
||||
if (handle.Cancelled) yield break;
|
||||
elapsed += Time.deltaTime;
|
||||
float t = Mathf.Clamp01(elapsed / duration);
|
||||
|
||||
// 每帧重新收集(Blend 模式下新 source 可能中途加入)
|
||||
elapsed += Time.deltaTime;
|
||||
|
||||
// 每帧收集当前活跃的 sources,并为新加入的 source 创建 tween
|
||||
sources.Clear();
|
||||
handle.CollectActiveSources(sources);
|
||||
|
||||
foreach (AudioSource src in sources)
|
||||
if (src) src.volume = Mathf.Lerp(0f, 1f, t);
|
||||
{
|
||||
if (!src) continue;
|
||||
|
||||
// 如果这个 source 还没被 tween 过,则创建一个 DOFade
|
||||
if (DOTween.IsTweening(src))
|
||||
continue;
|
||||
src.volume = 0f;
|
||||
src.DOFade(1f, duration - elapsed).SetEase(Ease.Linear);
|
||||
}
|
||||
|
||||
yield return null;
|
||||
}
|
||||
|
||||
// 确保最终音量准确
|
||||
// 确保最终音量
|
||||
sources.Clear();
|
||||
handle.CollectActiveSources(sources);
|
||||
foreach (AudioSource src in sources)
|
||||
|
||||
Reference in New Issue
Block a user