Files
Fishing2/Assets/Scripts/NBC/Sound/SoundManager.cs
2025-06-10 14:57:35 +08:00

93 lines
2.7 KiB
C#

using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Audio;
namespace NBC
{
public enum AudioChannelType
{
BGM,
SFX,
UI,
Ambient,
Player
}
public class SoundManager : MonoBehaviour
{
[Header("Mixer Settings")] public AudioMixer mixer;
[Header("Mixer Group Routing")] public AudioMixerGroup bgmGroup;
public AudioMixerGroup sfxGroup;
public AudioMixerGroup uiGroup;
public AudioMixerGroup ambientGroup;
public AudioMixerGroup playerGroup;
private Dictionary<AudioChannelType, AudioMixerGroup> groupMap;
public static SoundManager Inst { get; private set; }
private void Awake()
{
Inst = this;
Init();
}
public void Start()
{
Log.Info("UI 模块初始化");
}
void Init()
{
groupMap = new Dictionary<AudioChannelType, AudioMixerGroup>
{
{ AudioChannelType.BGM, bgmGroup },
{ AudioChannelType.SFX, sfxGroup },
{ AudioChannelType.UI, uiGroup },
{ AudioChannelType.Ambient, ambientGroup },
{ AudioChannelType.Player, playerGroup },
};
}
public void PlaySound(AudioClip clip, AudioChannelType type, Vector3 position = default, bool is3D = false)
{
if (clip == null) return;
GameObject go = new GameObject("Audio_" + clip.name);
go.transform.position = position;
AudioSource source = go.AddComponent<AudioSource>();
source.clip = clip;
source.outputAudioMixerGroup = groupMap[type];
source.spatialBlend = is3D ? 1f : 0f;
source.Play();
Destroy(go, clip.length + 0.5f); // 延迟销毁
}
public void SetVolume(AudioChannelType type, float volume01)
{
string exposedName = type + "Volume";
mixer.SetFloat(exposedName, Mathf.Log10(Mathf.Clamp01(volume01)) * 20);
}
public void SetMasterVolume(float volume01)
{
mixer.SetFloat("MasterVolume", Mathf.Log10(Mathf.Clamp01(volume01)) * 20);
}
// public void LoadVolumes()
// {
// foreach (AudioChannelType type in System.Enum.GetValues(typeof(AudioChannelType)))
// {
// string exposed = type + "Volume";
// float volume = PlayerPrefs.GetFloat(exposed, 1f);
// SetVolume(type, volume);
// }
//
// float master = PlayerPrefs.GetFloat("MasterVolume", 1f);
// SetMasterVolume(master);
// }
}
}