AudioMgr.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. /* 音频管理者 */
  5. public class AudioMgr : MonoBehaviour
  6. {
  7. private AudioSource audioSource;
  8. public static AudioMgr ins;
  9. public static bool openEffect = true;
  10. public static bool openBGM = true;
  11. public static void Init()
  12. {
  13. if (GameObject.Find("AudioMgr") == null) {
  14. GameObject audioMgr = new GameObject("AudioMgr");
  15. audioMgr.AddComponent<AudioMgr>();
  16. DontDestroyOnLoad(audioMgr);
  17. }
  18. }
  19. void Start() {
  20. ins = this;
  21. this.audioSource = this.gameObject.AddComponent<AudioSource>();
  22. openEffect = PlayerPrefs.GetInt("openEffect", 1) == 1 ? true: false;
  23. openBGM = PlayerPrefs.GetInt("openBGM", 1) == 1 ? true: false;
  24. }
  25. void OnDestroy()
  26. {
  27. PlayerPrefs.SetInt("openEffect", openEffect ? 1 : 0);
  28. PlayerPrefs.SetInt("openBGM", openBGM ? 1 : 0);
  29. }
  30. private void Play(string path, AudioSource audioSource) {
  31. AudioClip audioClip = Resources.Load<AudioClip>(path);
  32. if (audioSource == null) {
  33. audioSource = this.audioSource;
  34. }
  35. audioSource.clip = audioClip;
  36. if (openEffect) {
  37. audioSource.Play();
  38. }
  39. }
  40. public static AudioSource GetAudioSource(GameObject target) {
  41. AudioSource audioSource = target.GetComponent<AudioSource>();
  42. if (audioSource == null) {
  43. audioSource = target.AddComponent<AudioSource>();
  44. }
  45. return audioSource;
  46. }
  47. public void PlayShoot(AudioSource audioSource) {
  48. this.Play("Audios/shoot", audioSource);
  49. }
  50. public void PlayHit(AudioSource audioSource) {
  51. this.Play("Audios/hit", audioSource);
  52. }
  53. public void PlayCheer(bool cheer) {
  54. this.Play("Audios/" + (cheer ? "喝彩" : "喝倒彩"), null);
  55. }
  56. public void PlayBtn() {
  57. this.Play("Audios/btn", null);
  58. }
  59. public void PlayWin() {
  60. this.Play("Audios/win", null);
  61. }
  62. public void PlayArrowEnter() {
  63. this.Play("Audios/Animal/arrow_enter", null);
  64. }
  65. public void PlayAnimalEffect(string name, AudioSource audioSource) {
  66. this.Play("Audios/Animal/" + name, audioSource);
  67. }
  68. }