Files
CityBuilder/Assets/Scripts/AudioManager.cs

68 lines
1.9 KiB
C#

using UnityEngine;
public class AudioManager : MonoBehaviour
{
[SerializeField] private AudioSource[] backgroundMusicSource;
[SerializeField] private AudioSource[] soundEffectsSource;
private int[] randomizedIndices;
private int currentIndex = 0;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
RandomizeBackgroundMusicOrder();
PlayNextBackgroundMusic();
}
// Update is called once per frame
void Update()
{
}
public void PlayBackgroundMusic(int index)
{
if (index < 0 || index >= backgroundMusicSource.Length)
{
Debug.LogWarning("Invalid background music index.");
return;
}
backgroundMusicSource[index].Play();
}
private void RandomizeBackgroundMusicOrder()
{
randomizedIndices = new int[backgroundMusicSource.Length];
for (int i = 0; i < backgroundMusicSource.Length; i++)
{
randomizedIndices[i] = i;
}
// Shuffle the array
for (int i = randomizedIndices.Length - 1; i > 0; i--)
{
int randomIndex = Random.Range(0, i + 1);
int temp = randomizedIndices[i];
randomizedIndices[i] = randomizedIndices[randomIndex];
randomizedIndices[randomIndex] = temp;
}
}
private void PlayNextBackgroundMusic()
{
if (backgroundMusicSource.Length == 0) return;
backgroundMusicSource[randomizedIndices[currentIndex]].Play();
currentIndex++;
if (currentIndex >= randomizedIndices.Length)
{
currentIndex = 0;
RandomizeBackgroundMusicOrder();
}
// Schedule the next track to play after the current one finishes
float clipLength = backgroundMusicSource[randomizedIndices[currentIndex]].clip.length;
Invoke(nameof(PlayNextBackgroundMusic), clipLength);
}
}