AudioManager.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. namespace DuckHunter
  5. {
  6. public class AudioManager : MonoBehaviour
  7. {
  8. private AudioSource _audioSource;
  9. private static AudioManager _Instance;
  10. public static AudioManager Instance
  11. {
  12. get
  13. {
  14. if (!_Instance) new GameObject(typeof(AudioManager).Name).AddComponent<AudioManager>();
  15. return _Instance;
  16. }
  17. }
  18. void Awake()
  19. {
  20. _Instance = this;
  21. _audioSource = gameObject.AddComponent<AudioSource>();
  22. }
  23. void OnDestroy()
  24. {
  25. if (_Instance == this) _Instance = null;
  26. }
  27. public void PlayShoot(GameObject target)
  28. {
  29. PlayAudio("DuckHunter/Audios/Shoot", GetAudioSource(target));
  30. }
  31. public void PlayDuckHit(GameObject target)
  32. {
  33. PlayAudio("DuckHunter/Audios/DuckHit", GetAudioSource(target));
  34. }
  35. public void PlayDogTaunt(GameObject target)
  36. {
  37. PlayAudio("DuckHunter/Audios/DogTaunt", GetAudioSource(target));
  38. }
  39. public void PlayDogHappy(GameObject target)
  40. {
  41. PlayAudio("DuckHunter/Audios/DogHappy", GetAudioSource(target));
  42. }
  43. public void PlayGameStart()
  44. {
  45. PlayAudio("DuckHunter/Audios/GameStart", null);
  46. }
  47. public void PlayGameOver()
  48. {
  49. PlayAudio("DuckHunter/Audios/GameOver", null);
  50. }
  51. public void PlayGamePass()
  52. {
  53. PlayAudio("DuckHunter/Audios/GamePass", null);
  54. }
  55. public void PlayFullScore()
  56. {
  57. PlayAudio("DuckHunter/Audios/FullScore", null);
  58. }
  59. public void PlayBtn()
  60. {
  61. AudioMgr.ins.PlayBtn();
  62. // PlayAudio("DuckHunter/Audios/Btn", null);
  63. }
  64. private void PlayAudio(string audioPath, AudioSource audioSource)
  65. {
  66. AudioClip audioClip = Resources.Load<AudioClip>(audioPath);
  67. if (audioSource == null) audioSource = _audioSource;
  68. audioSource.clip = audioClip;
  69. audioSource.Play();
  70. }
  71. private AudioSource GetAudioSource(GameObject target)
  72. {
  73. if (target == null) return null;
  74. AudioSource audioSource = target.GetComponent<AudioSource>();
  75. if (audioSource == null) audioSource = target.AddComponent<AudioSource>();
  76. return audioSource;
  77. }
  78. }
  79. }