RiftMayhem/Assets/Audio/Scripts/EnhancedAudioSource.cs
2025-06-08 12:18:13 +01:00

69 lines
1.7 KiB
C#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(AudioSource))]
[RequireComponent(typeof(AudioClipRandomizer))]
[RequireComponent(typeof(PitchRandomizer))]
public class EnhancedAudioSource : MonoBehaviour
{
[Header("Use this config instead of default audiosource")]
[Header("Config:")]
[SerializeField] private bool randomizePitch;
[SerializeField] private bool randomizeClip;
[Tooltip("This will always override playOnAwake")]
[SerializeField] private bool playOnSpawn;
[SerializeField] private bool loop;
[SerializeField] private bool loopButRandom;
AudioSource source;
AudioClipRandomizer clipRandomizer;
PitchRandomizer pitchRandomizer;
float loopingButRandomLength;
private void Awake()
{
source = GetComponent<AudioSource>();
clipRandomizer = GetComponent<AudioClipRandomizer>();
pitchRandomizer = GetComponent<PitchRandomizer>();
source.playOnAwake = false;
source.loop = loop;
}
private void Start()
{
if (playOnSpawn)
Play();
}
public void Play()
{
if (randomizeClip)
clipRandomizer.RandomizeClip();
else
clipRandomizer.PickFirst();
if (randomizePitch)
pitchRandomizer.RandomizePitch();
source.Play();
Debug.Log("Played Enhanced AudioSource with clip: " + source.clip.name);
if(loopButRandom)
{
StartCoroutine(LoopRandom());
}
}
IEnumerator LoopRandom()
{
loopingButRandomLength = source.clip.length;
yield return new WaitForSeconds(loopingButRandomLength);
Play();
}
}