Files
beyond/Assets/Scripts/Audio/TriggerSoundByEvent.cs
2024-11-20 15:21:28 +01:00

86 lines
2.3 KiB
C#

using Invector;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Audio;
using Lean.Pool;
namespace Beyond
{
public class TriggerSoundByEvent : MonoBehaviour
{
public GameObject audioSource;
public AudioMixerGroup audioMixerGroup;
public List<AudioClip> sounds;
[Header("Trigger Delay")]
public float triggerTime;
private vFisherYatesRandom _random;
public void TriggerSound()
{
if (sounds.Count == 0)
{
return;
}
StartCoroutine(TriggerSoundDelay(triggerTime));
}
#if UNITY_EDITOR
private void Awake()
{
testAudio = false;
}
[SerializeField, Header("Debug, for testing audio")]
private bool testAudio;
private void Update()
{
if (testAudio)
{
testAudio = false;
TriggerSound();
}
}
#endif
private IEnumerator TriggerSoundDelay(float delay)
{
yield return new WaitForSeconds(delay);
if (_random == null)
_random = new vFisherYatesRandom();
GameObject audioObject = null;
if (audioSource != null)
{
audioObject = LeanPool.Spawn(audioSource.gameObject, transform.position, Quaternion.identity);
}
else
{
Debug.Log("Cant pool object");
}
if (audioObject != null)
{
var source = audioObject.gameObject.GetComponent<AudioSource>();
var clip = sounds[_random.Next(sounds.Count)];
if (audioMixerGroup != null)
{
source.outputAudioMixerGroup = audioMixerGroup;
}
var destroy = audioObject.GetComponent<DespawnGameObject>();
if (destroy)
{
destroy.delay = clip.length;
}
else
{
destroy = audioObject.AddComponent<DespawnGameObject>();
destroy.delay = clip.length;
}
source.clip = clip; //to see in inspector;
source.PlayOneShot(clip);
}
}
}
}