48 lines
1.1 KiB
C#
48 lines
1.1 KiB
C#
using System.Collections;
|
|
using UnityEngine;
|
|
using UnityEngine.Rendering;
|
|
|
|
/// <summary>
|
|
/// Smoothly fades a post-process Volume's weight in or out (e.g. from UnityEvents when the player
|
|
/// changes area), instead of switching the look abruptly.
|
|
/// </summary>
|
|
[RequireComponent(typeof(Volume))]
|
|
public class VolumeWeightFader : MonoBehaviour
|
|
{
|
|
[SerializeField, Min(0f)] private float _duration = 1.5f;
|
|
|
|
private Volume _volume;
|
|
private Coroutine _fade;
|
|
|
|
private void Awake()
|
|
{
|
|
_volume = GetComponent<Volume>();
|
|
}
|
|
|
|
public void FadeIn() => FadeTo(1f);
|
|
|
|
public void FadeOut() => FadeTo(0f);
|
|
|
|
public void FadeTo(float weight)
|
|
{
|
|
if (_fade != null)
|
|
StopCoroutine(_fade);
|
|
|
|
_fade = StartCoroutine(Fade(Mathf.Clamp01(weight)));
|
|
}
|
|
|
|
private IEnumerator Fade(float target)
|
|
{
|
|
float start = _volume.weight;
|
|
|
|
for (float t = 0f; t < _duration; t += Time.deltaTime)
|
|
{
|
|
_volume.weight = Mathf.Lerp(start, target, Mathf.SmoothStep(0f, 1f, t / _duration));
|
|
yield return null;
|
|
}
|
|
|
|
_volume.weight = target;
|
|
_fade = null;
|
|
}
|
|
}
|