using UnityEngine; using UnityEngine.UI; using TMPro; /// /// 音量设置面板 /// 提供系统音量调节功能 /// public class VolumeSettingPanel : BasePanel { [Header("音量控制")] public Slider VolumeSlider; public TextMeshProUGUI VolumeText; public Button TestSoundButton; [Header("按钮")] public Button HomeButton; public Button ConfirmButton; public Button BackButton; private SettingsViewModel _vm; private AudioSource _testAudioSource; public override void Init() { _vm = new SettingsViewModel(); InitializeUI(); SetupAudioTest(); } private void InitializeUI() { // 初始化滑块值 if (VolumeSlider != null) { VolumeSlider.minValue = 10; VolumeSlider.maxValue = 100; VolumeSlider.wholeNumbers = true; VolumeSlider.value = Mathf.Clamp(_vm.Volume, 10, 100); // 监听滑块变化 VolumeSlider.onValueChanged.AddListener(OnVolumeChanged); } // 初始化文本显示 int initialVolume = VolumeSlider != null ? (int)VolumeSlider.value : Mathf.Clamp(_vm.Volume, 10, 100); UpdateVolumeText(initialVolume); SyncMainPanelVolume(initialVolume); // 按钮事件 if (HomeButton != null) { HomeButton.onClick.AddListener(() => { ConfirmDialog.Show("确认", "是否返回主界面?", () => { ReturnToHome(); }); }); } if (ConfirmButton != null) { ConfirmButton.onClick.AddListener(ApplyAndBack); } if (BackButton != null) { BackButton.onClick.AddListener(() => ConfirmDialog.Show("确认", "是否返回设置界面?", () => { ClosePanel(); ClosePanel(); }) ); } if (TestSoundButton != null) { TestSoundButton.onClick.AddListener(PlayTestSound); } } private void SetupAudioTest() { // 创建测试音频源 var audioGO = new GameObject("TestAudioSource"); audioGO.transform.SetParent(transform); _testAudioSource = audioGO.AddComponent(); // 加载测试音频clip(如果存在) var testClip = Resources.Load("Audio/DiDi"); if (testClip != null) { _testAudioSource.clip = testClip; } _testAudioSource.playOnAwake = false; } private void OnVolumeChanged(float value) { int volumePercent = (int)value; UpdateVolumeText(volumePercent); SyncMainPanelVolume(volumePercent); // 实时更新测试音频源的音量 if (_testAudioSource != null) { _testAudioSource.volume = value / 100f; } // 可选:实时应用系统音量(但可能会造成频繁调用) // 建议只在确认时应用,这里仅作预览 // Debug.Log($"VolumeSettingPanel: 音量预览 {volumePercent}%"); } private void UpdateVolumeText(int volume) { if (VolumeText != null) { VolumeText.text = $"{volume}%"; } } private void SyncMainPanelVolume(int volumePercent) { var mainPanel = UIManager.Instance.GetPanel(); if (mainPanel != null) { mainPanel.UpdateAudioVolume(volumePercent); } } private void PlayTestSound() { if (_testAudioSource != null && _testAudioSource.clip != null) { _testAudioSource.Play(); } else { // 如果没有测试音频,创建一个简单的提示音 Debug.Log($"播放测试音 - 当前音量: {VolumeSlider.value}%"); // 可以在这里集成系统提示音或生成简单音频 } } private void ApplyAndBack() { if (VolumeSlider != null) { int finalVolume = (int)VolumeSlider.value; _vm.Volume = finalVolume; SyncMainPanelVolume(finalVolume); Debug.Log($"VolumeSettingPanel: 应用音量设置 {finalVolume}%"); } ClosePanel(); } void OnDestroy() { // 清理音频资源 if (_testAudioSource != null) { Destroy(_testAudioSource.gameObject); } } }