Created
December 3, 2021 08:12
-
-
Save DmitriyProkopyev/28227b623bcc3b9cf3b8f7f6d658141e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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