Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save DmitriyProkopyev/28227b623bcc3b9cf3b8f7f6d658141e to your computer and use it in GitHub Desktop.
Save DmitriyProkopyev/28227b623bcc3b9cf3b8f7f6d658141e to your computer and use it in GitHub Desktop.
using System;
using System.Collections;
using UnityEngine;
[RequireComponent(typeof(AudioSource))]
public class Alarm : MonoBehaviour
{
[SerializeField] private float _changingSpeed;
[SerializeField] private float _delay;
private AudioSource _audioSource;
private Coroutine _coroutine;
private void Start() => _audioSource = GetComponent<AudioSource>();
private void OnTriggerEnter(Collider other)
{
if (other.TryGetComponent(out Player _) == false)
return;
if (_coroutine != null)
StopCoroutine(_coroutine);
_coroutine = StartCoroutine(FadeVolume(1));
}
private void OnTriggerExit(Collider other)
{
if (other.TryGetComponent(out Player player) == false)
return;
if (_coroutine != null)
StopCoroutine(_coroutine);
_coroutine = StartCoroutine(FadeVolume(0));
}
private IEnumerator FadeVolume(float targetVolume)
{
if (targetVolume < 0 || targetVolume > 1f)
throw new ArgumentOutOfRangeException(nameof(targetVolume));
var wait = new WaitForSeconds(_delay);
while (Mathf.Approximately(_audioSource.volume, targetVolume) == false)
{
_audioSource.volume = Mathf.MoveTowards(_audioSource.volume, targetVolume, _changingSpeed);
yield return wait;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment