using System.Collections; using UnityEngine; using UnityEngine.Rendering; /// /// 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. /// [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(); } 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; } }