AudioMgr.cs 2.0 KB

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