SoundManager.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using UnityEngine;
  5. /// <summary>
  6. /// 声音管理类
  7. /// </summary>
  8. public class SoundManager : MonoSingleton<SoundManager>
  9. {
  10. #region 数据成员
  11. //背景音乐播放组件
  12. private AudioSource m_bgSound;
  13. //音效播放组件
  14. private AudioSource m_effectSound;
  15. //静音管理
  16. private bool mute = false;
  17. public bool Mute
  18. {
  19. get
  20. {
  21. return mute;
  22. }
  23. set
  24. {
  25. m_bgSound.mute = value;
  26. m_effectSound.mute = value;
  27. mute = value;
  28. }
  29. }
  30. //音乐大小
  31. public float BgVolume
  32. {
  33. get { return m_bgSound.volume; }
  34. set { m_bgSound.volume = value; }
  35. }
  36. //音效大小
  37. public float EffectVolume
  38. {
  39. get { return m_effectSound.volume; }
  40. set { m_effectSound.volume = value; }
  41. }
  42. #endregion
  43. /// <summary>
  44. /// 在Awake中添加两个音频播放器并初始化
  45. /// </summary>
  46. protected void Awake()
  47. {
  48. m_bgSound = this.gameObject.AddComponent<AudioSource>();
  49. m_bgSound.playOnAwake = false;
  50. m_bgSound.loop = false;
  51. m_effectSound = this.gameObject.AddComponent<AudioSource>();
  52. m_effectSound.playOnAwake = false;
  53. }
  54. /// <summary>
  55. /// 播放BGM
  56. /// </summary>
  57. /// <param name="audioName"></param>
  58. public void PlayBg(AudioClip audioClip)
  59. {
  60. if (Mute)
  61. return;
  62. //播放
  63. if (audioClip != null)
  64. {
  65. m_bgSound.clip = audioClip;
  66. m_bgSound.Play();
  67. }
  68. }
  69. /// <summary>
  70. /// 停止BGM
  71. /// </summary>
  72. public void StopBg()
  73. {
  74. if (m_bgSound.clip != null)
  75. {
  76. m_bgSound.Stop();
  77. m_bgSound.clip = null;
  78. }
  79. }
  80. public void RePlay()
  81. {
  82. if (m_bgSound.clip != null)
  83. {
  84. m_bgSound.Play();
  85. }
  86. }
  87. public void Pause()
  88. {
  89. if (m_bgSound.clip != null)
  90. {
  91. m_bgSound.Pause();
  92. }
  93. }
  94. /// <summary>
  95. /// 播放音效
  96. /// </summary>
  97. /// <param name="audioName"></param>
  98. public void PlayEffect(AudioClip audioClip)
  99. {
  100. if (Mute)
  101. return;
  102. //播放
  103. m_effectSound.PlayOneShot(audioClip);
  104. }
  105. /// <summary>
  106. /// 静音方法
  107. /// </summary>
  108. public void OnMuteButtonDown()
  109. {
  110. Mute = true;
  111. }
  112. /// <summary>
  113. /// 取消静音
  114. /// </summary>
  115. public void OnNotMuteButtonDown()
  116. {
  117. Mute = false;
  118. }
  119. }