cvr-props/Assets/ABI.CCK/Components/CVRAudioDriver.cs

95 lines
2.5 KiB
C#
Raw Permalink Normal View History

2023-01-22 16:38:23 +01:00
using System.Collections.Generic;
using JetBrains.Annotations;
2023-01-22 16:38:23 +01:00
using UnityEngine;
namespace ABI.CCK.Components
{
[HelpURL("https://developers.abinteractive.net/cck/components/audio-driver/")]
public class CVRAudioDriver : MonoBehaviour, ICCK_Component
2023-01-22 16:38:23 +01:00
{
public AudioSource audioSource;
[SerializeField]
2023-01-22 16:38:23 +01:00
public List<AudioClip> audioClips = new List<AudioClip>();
public int selectedAudioClip;
2023-01-22 16:38:23 +01:00
public bool playOnSwitch = true;
private int _selectedAudioClip;
2023-01-22 16:38:23 +01:00
#region Unity Events
private void OnValidate() => CheckAndUpdateAudioClip(); // Editor testing
private void OnDidApplyAnimationProperties() => CheckAndUpdateAudioClip();
2023-01-22 16:38:23 +01:00
#endregion
2023-01-22 16:38:23 +01:00
#region Public Methods
2023-01-22 16:38:23 +01:00
[PublicAPI]
2023-01-22 16:38:23 +01:00
public void PlaySound(int index)
=> SetAndMaybePlay(index);
[PublicAPI]
2023-01-22 16:38:23 +01:00
public void PlaySound()
{
if (audioSource != null && audioSource.isActiveAndEnabled)
audioSource.Play();
2023-01-22 16:38:23 +01:00
}
[PublicAPI]
2023-01-22 16:38:23 +01:00
public void PlayNext()
{
if (_selectedAudioClip + 1 >= audioClips.Count)
PlaySound(0);
else
PlaySound(_selectedAudioClip + 1);
}
[PublicAPI]
2023-01-22 16:38:23 +01:00
public void PlayPrev()
{
if (_selectedAudioClip == 0)
PlaySound(audioClips.Count - 1);
else
PlaySound(_selectedAudioClip - 1);
}
[PublicAPI]
2023-01-22 16:38:23 +01:00
public void SelectRandomSound()
=> SetAndMaybePlay(Random.Range(0, audioClips.Count));
#endregion
#region Private Methods
private void CheckAndUpdateAudioClip()
{
if (selectedAudioClip != _selectedAudioClip)
SetAndMaybePlay(selectedAudioClip);
}
private void SetAndMaybePlay(int index)
2023-01-22 16:38:23 +01:00
{
if (SetAudioClip(index) && playOnSwitch)
PlaySound();
2023-01-22 16:38:23 +01:00
}
private bool SetAudioClip(int index)
{
_selectedAudioClip = index;
if (index >= audioClips.Count
|| index < 0)
return false;
if (audioClips[index] == null
|| audioSource == null)
return false;
audioSource.clip = audioClips[index];
return true;
}
#endregion
2023-01-22 16:38:23 +01:00
}
}