100 lines
2.5 KiB
C#
100 lines
2.5 KiB
C#
using UnityEngine;
|
|
|
|
public class AudioManager : MonoBehaviour
|
|
{
|
|
public static AudioManager instance;
|
|
void Awake()
|
|
{
|
|
if (instance == null)
|
|
{
|
|
instance = this;
|
|
DontDestroyOnLoad(gameObject); // Ensure this persists across scenes
|
|
}
|
|
else if (instance != this)
|
|
{
|
|
Destroy(gameObject); // Ensure only one instance exists
|
|
}
|
|
}
|
|
|
|
public AudioSource mainMenuMusic, victoryMusic, defeatMusic, battleSelectMusic;
|
|
public AudioSource[] backgroundMusic;
|
|
public AudioSource[] sfx;
|
|
private int currentBackgroundIndex;
|
|
private bool isBackgroundMusicPlaying;
|
|
// Start is called once before the first execution of Update after the MonoBehaviour is created
|
|
void Start()
|
|
{
|
|
|
|
}
|
|
|
|
// Update is called once per frame
|
|
void Update()
|
|
{
|
|
if (isBackgroundMusicPlaying)
|
|
{
|
|
if (!backgroundMusic[currentBackgroundIndex].isPlaying)
|
|
{
|
|
currentBackgroundIndex++;
|
|
if (currentBackgroundIndex >= backgroundMusic.Length)
|
|
{
|
|
currentBackgroundIndex = 0; // Loop back to the first track
|
|
}
|
|
backgroundMusic[currentBackgroundIndex].Play();
|
|
}
|
|
}
|
|
}
|
|
|
|
public void StopMusic()
|
|
{
|
|
mainMenuMusic.Stop();
|
|
victoryMusic.Stop();
|
|
defeatMusic.Stop();
|
|
foreach (AudioSource track in backgroundMusic)
|
|
{
|
|
track.Stop();
|
|
}
|
|
isBackgroundMusicPlaying = false;
|
|
}
|
|
|
|
public void PlayMainMenuMusic()
|
|
{
|
|
StopMusic();
|
|
mainMenuMusic.Play();
|
|
}
|
|
|
|
public void PlayVictoryMusic()
|
|
{
|
|
StopMusic();
|
|
victoryMusic.Play();
|
|
}
|
|
|
|
public void PlayDefeatMusic()
|
|
{
|
|
StopMusic();
|
|
defeatMusic.Play();
|
|
}
|
|
public void PlayBattleSelectMusic()
|
|
{
|
|
StopMusic();
|
|
battleSelectMusic.Play();
|
|
}
|
|
public void PlayBackgroundMusic(int index)
|
|
{
|
|
StopMusic();
|
|
currentBackgroundIndex = Random.Range(0, backgroundMusic.Length);
|
|
backgroundMusic[currentBackgroundIndex].Play();
|
|
isBackgroundMusicPlaying = true;
|
|
}
|
|
|
|
public void PlaySFX(int sfxToPlay)
|
|
{
|
|
if (sfxToPlay >= 0 && sfxToPlay < sfx.Length)
|
|
{
|
|
// Stop all SFX before playing a new one
|
|
sfx[sfxToPlay].Stop();
|
|
// Play the selected SFX
|
|
sfx[sfxToPlay].Play();
|
|
}
|
|
}
|
|
}
|