驱蚊app
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 
 
 

100 行
2.3 KiB

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. public class AudioManager : MonoBehaviour
  5. {
  6. public static AudioManager Instance { get; private set; }
  7. private AudioSource bgmSource;
  8. private List<AudioSource> sfxSources = new List<AudioSource>();
  9. [Header("音量设置")]
  10. [Range(0f, 1f)] public float bgmVolume = 1f;
  11. [Range(0f, 1f)] public float sfxVolume = 1f;
  12. private void Awake()
  13. {
  14. if (Instance != null)
  15. {
  16. Destroy(gameObject);
  17. return;
  18. }
  19. Instance = this;
  20. DontDestroyOnLoad(gameObject);
  21. bgmSource = gameObject.AddComponent<AudioSource>();
  22. bgmSource.loop = true;
  23. }
  24. public void PlayBGM(string bgmName)
  25. {
  26. AudioClip clip = Resources.Load<AudioClip>($"Audio/{bgmName}");
  27. if (clip == null)
  28. {
  29. Debug.LogWarning($"未找到BGM: {bgmName}");
  30. return;
  31. }
  32. bgmSource.clip = clip;
  33. bgmSource.volume = bgmVolume;
  34. bgmSource.Play();
  35. }
  36. public void StopBGM()
  37. {
  38. bgmSource.Stop();
  39. }
  40. public void PlaySFX(string sfxName)
  41. {
  42. AudioClip clip = Resources.Load<AudioClip>($"Audio/{sfxName}");
  43. if (clip == null)
  44. {
  45. Debug.LogWarning($"未找到音效: {sfxName}");
  46. return;
  47. }
  48. AudioSource source = gameObject.AddComponent<AudioSource>();
  49. source.clip = clip;
  50. source.volume = sfxVolume;
  51. source.Play();
  52. sfxSources.Add(source);
  53. StartCoroutine(DestroySFXWhenDone(source));
  54. }
  55. private IEnumerator DestroySFXWhenDone(AudioSource source)
  56. {
  57. yield return new WaitForSeconds(source.clip.length);
  58. sfxSources.Remove(source);
  59. Destroy(source);
  60. }
  61. public void SetVolume(SoundType type, float volume)
  62. {
  63. if (type == SoundType.BGM)
  64. {
  65. bgmVolume = volume;
  66. bgmSource.volume = volume;
  67. }
  68. else if (type == SoundType.SFX)
  69. {
  70. sfxVolume = volume;
  71. foreach (var source in sfxSources)
  72. {
  73. source.volume = volume;
  74. }
  75. }
  76. }
  77. public void Mute(bool mute)
  78. {
  79. bgmSource.mute = mute;
  80. foreach (var source in sfxSources)
  81. {
  82. source.mute = mute;
  83. }
  84. }
  85. }