Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- using System.Collections;
- //This One shot audio is meant as an alternative on the default unity One Shot Audio.
- //With this version you can use different pitches and a reference to the oneshot can be kept, so that volume can be altered while playing.
- public class OneShotAudio : MonoBehaviour {
- [SerializeField]
- private AudioSource _gameAudio = null;
- private bool _playing;
- private Coroutine _destructionCoroutine;
- //The script that has called the one shot.
- private IOneShotAudioOwner _owner;
- public float Volume
- {
- get { return _gameAudio.volume; }
- set { _gameAudio.volume = value; }
- }
- public void StartPlayingSound(AudioClip audioClip,float volume,IOneShotAudioOwner owner,float pitch=1f)
- {
- if (!CheckIfValid())
- {
- Destroy(gameObject);
- return;
- }
- if (audioClip == null)
- {
- DestroyAudio();
- return;
- }
- _gameAudio.clip = audioClip;
- _gameAudio.volume = volume;
- _gameAudio.pitch = pitch;
- _owner = owner;
- SetPlaying(true);
- }
- public void StartPlayingSound(AudioClip audioClip, float unscaledVolume, float pitch = 1f)
- {
- StartPlayingSound(audioClip, unscaledVolume, null,pitch);
- }
- //Check if there is an audiosource.
- private bool CheckIfValid()
- {
- if (_gameAudio == null)
- {
- Debug.LogError(gameObject.name+" lacks an Audio source!");
- return false;
- }
- return true;
- }
- IEnumerator StartTimedDestroy()
- {
- //Wait until the clip is done with playing to destroy
- while (_gameAudio.isPlaying||_gameAudio.timeSamples>0)
- {
- yield return null;
- }
- DestroyAudio();
- }
- void DestroyAudio()
- {
- SetPlaying(false);
- if (_owner != null) _owner.OneShotAudioGetsDestroyed(this);
- AudioManager.PutBackOnOneShotAudioPool(this);
- }
- public void Reset()
- {
- SetPlaying(false);
- }
- private void SetPlaying(bool playing)
- {
- if(playing==_playing)return;
- _playing = playing;
- if (_playing)
- {
- _gameAudio.Play();
- //Prepare for destruction when done
- if (_destructionCoroutine != null) StopCoroutine(_destructionCoroutine);
- _destructionCoroutine=StartCoroutine(StartTimedDestroy());
- AudioManager.AddGameAudio(_gameAudio);
- }
- else
- {
- AudioManager.RemoveGameAudio(_gameAudio);
- //Stop destruction
- if (_destructionCoroutine != null)
- {
- _gameAudio.Stop();
- StopCoroutine(_destructionCoroutine);
- _destructionCoroutine = null;
- }
- }
- }
- }
- public interface IOneShotAudioOwner
- {
- //This is so that the owner knows the oneshot is done. So that by example references can get cleaned
- void OneShotAudioGetsDestroyed(OneShotAudio audio);
- }
Add Comment
Please, Sign In to add comment