BloodAndGore/Assets/Scripts/Audio/MusicPlayer.cs

88 lines
3.0 KiB
C#

using UnityEngine;
using UnityEngine.SceneManagement;
using Saltosion.OneWeapon.Utils;
namespace Saltosion.OneWeapon.Audio {
public enum MusicTrack {
None = -1,
Elevator = 0,
SetFireToReality, // 1, and so on
SpaceDimensions,
ThrustSequence,
}
public enum AmbienceTrack {
None = -1,
Dark = 0,
}
enum Channel {
Music, Ambience, Count
}
public class MusicPlayer : MonoBehaviour {
private static MusicPlayer Singleton;
private static int SingletonSceneIndex = -1;
[Header("Audio files")]
public AudioClip[] MusicClips;
public AudioClip[] AmbienceClips;
[Header("Other")]
public MusicChannelPlayer ChannelPlayerForMusic;
public MusicChannelPlayer ChannelPlayerForAmbience;
public MusicTrack DebugMusicTrack = MusicTrack.None;
public bool DebugSetMusicTrack = false;
public AmbienceTrack DebugAmbienceTrack = AmbienceTrack.None;
public bool DebugSetAmbienceTrack = false;
private MusicChannelPlayer[] Channels;
private void Start() {
int Index = SceneManager.GetActiveScene().buildIndex;
if (SingletonSceneIndex == Index) {
Debug.LogWarning($"The scene '{SceneManager.GetActiveScene().name}' has multiple MusicPlayers!\nOnly the last to run Start() will be used.");
}
SingletonSceneIndex = Index;
Singleton = this;
Channels = new MusicChannelPlayer[(int)Channel.Count];
Channels[(int)Channel.Music] = ChannelPlayerForMusic;
Channels[(int)Channel.Ambience] = ChannelPlayerForAmbience;
}
private void Update() {
ChannelPlayerForMusic.Volume = Options.MusicVolume;
ChannelPlayerForAmbience.Volume = Options.AmbienceVolume;
if (DebugSetMusicTrack) {
DebugSetMusicTrack = false;
SetMusicTrack(DebugMusicTrack, true);
}
if (DebugSetAmbienceTrack) {
DebugSetAmbienceTrack = false;
SetAmbienceTrack(DebugAmbienceTrack, true);
}
}
private void SetChannelTrack(Channel channel, AudioClip clip, bool fade) {
int channelIndex = (int)channel;
if (Channels[channelIndex].CurrentlyPlaying) {
Channels[channelIndex].FadingOut = fade;
}
if (clip != null) {
Channels[channelIndex].FadingIn = fade;
Channels[channelIndex].NextClip = clip;
}
}
public static void SetMusicTrack(MusicTrack track, bool fade) {
Singleton.SetChannelTrack(Channel.Music, track == MusicTrack.None ? null : Singleton.MusicClips[(int)track], fade);
}
public static void SetAmbienceTrack(AmbienceTrack track, bool fade) {
Singleton.SetChannelTrack(Channel.Ambience, track == AmbienceTrack.None ? null : Singleton.AmbienceClips[(int)track], fade);
}
}
}