| | | 1 | | using UnityEngine; |
| | | 2 | | |
| | | 3 | | /// <summary> |
| | | 4 | | /// Play a long continuous sound |
| | | 5 | | /// </summary> |
| | | 6 | | [RequireComponent(typeof(AudioSource))] |
| | | 7 | | public class PlayContinuousSound : MonoBehaviour |
| | | 8 | | { |
| | | 9 | | [Tooltip("The sound that is played")] |
| | 4 | 10 | | public AudioClip sound = null; |
| | | 11 | | |
| | | 12 | | [Tooltip("Controls if the sound plays on start")] |
| | 4 | 13 | | public bool playOnStart = false; |
| | | 14 | | |
| | | 15 | | [Tooltip("The volume of the sound")] |
| | 4 | 16 | | public float volume = 1.0f; |
| | | 17 | | |
| | 4 | 18 | | private AudioSource audioSource = null; |
| | 4 | 19 | | private MonoBehaviour currentOwner = null; |
| | | 20 | | |
| | | 21 | | private void Awake() |
| | 2 | 22 | | { |
| | 2 | 23 | | audioSource = GetComponent<AudioSource>(); |
| | 2 | 24 | | audioSource.volume = volume; |
| | 2 | 25 | | } |
| | | 26 | | |
| | | 27 | | private void Start() |
| | 2 | 28 | | { |
| | 2 | 29 | | if (playOnStart) |
| | 0 | 30 | | Play(); |
| | 2 | 31 | | } |
| | | 32 | | |
| | | 33 | | public void Play() |
| | 2 | 34 | | { |
| | 2 | 35 | | audioSource.clip = sound; |
| | 2 | 36 | | audioSource.Play(); |
| | 2 | 37 | | } |
| | | 38 | | |
| | | 39 | | public void Pause() |
| | 2 | 40 | | { |
| | 2 | 41 | | audioSource.clip = null; |
| | 2 | 42 | | audioSource.Pause(); |
| | 2 | 43 | | } |
| | | 44 | | |
| | | 45 | | public void PlayWithExclusivity(MonoBehaviour owner) |
| | 0 | 46 | | { |
| | 0 | 47 | | if (currentOwner == null) |
| | 0 | 48 | | { |
| | 0 | 49 | | currentOwner = owner; |
| | 0 | 50 | | Play(); |
| | 0 | 51 | | } |
| | 0 | 52 | | } |
| | | 53 | | |
| | | 54 | | public void StopWithExclusivity(MonoBehaviour owner) |
| | 0 | 55 | | { |
| | 0 | 56 | | if (currentOwner == owner) |
| | 0 | 57 | | { |
| | 0 | 58 | | currentOwner = null; |
| | 0 | 59 | | Pause(); |
| | 0 | 60 | | } |
| | 0 | 61 | | } |
| | | 62 | | |
| | | 63 | | public void TogglePlay() |
| | 0 | 64 | | { |
| | 0 | 65 | | bool isPlaying = !IsPlaying(); |
| | 0 | 66 | | SetPlay(isPlaying); |
| | 0 | 67 | | } |
| | | 68 | | |
| | | 69 | | public void SetPlay(bool playAudio) |
| | 0 | 70 | | { |
| | 0 | 71 | | if (playAudio) |
| | 0 | 72 | | { |
| | 0 | 73 | | Play(); |
| | 0 | 74 | | } |
| | | 75 | | else |
| | 0 | 76 | | { |
| | 0 | 77 | | Pause(); |
| | 0 | 78 | | } |
| | 0 | 79 | | } |
| | | 80 | | |
| | | 81 | | public bool IsPlaying() |
| | 0 | 82 | | { |
| | 0 | 83 | | return audioSource.isPlaying; |
| | 0 | 84 | | } |
| | | 85 | | |
| | | 86 | | public void SetClip(AudioClip audioClip) |
| | 0 | 87 | | { |
| | 0 | 88 | | sound = audioClip; |
| | 0 | 89 | | } |
| | | 90 | | |
| | | 91 | | private void OnValidate() |
| | 4 | 92 | | { |
| | 4 | 93 | | AudioSource audioSource = GetComponent<AudioSource>(); |
| | 4 | 94 | | audioSource.playOnAwake = false; |
| | 4 | 95 | | audioSource.loop = true; |
| | 4 | 96 | | } |
| | | 97 | | } |