UIPlaySound.cs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. using UnityEngine;
  2. using System.Collections;
  3. public class UIPlaySound : MonoBehaviour
  4. {
  5. public const string CommonClickSound = "UI_Click";
  6. public enum Trigger
  7. {
  8. OnClick,
  9. Custom,
  10. OnEnable,
  11. OnDisable,
  12. }
  13. public Trigger trigger = Trigger.OnClick;
  14. public string soundName = "";
  15. public float delayPlayTime = 0;
  16. private bool CanPlay
  17. {
  18. get
  19. {
  20. if (!enabled) return false;
  21. return true;
  22. }
  23. }
  24. private Coroutine mCor = null;
  25. void OnEnable()
  26. {
  27. if (trigger == Trigger.OnEnable)
  28. PlaySound();
  29. }
  30. void OnDisable()
  31. {
  32. if (trigger == Trigger.OnDisable)
  33. PlaySound();
  34. }
  35. void OnDestroy()
  36. {
  37. if (mCor != null)
  38. {
  39. StopCoroutine(mCor);
  40. mCor = null;
  41. }
  42. }
  43. public void OnClick()
  44. {
  45. PlaySound();
  46. }
  47. void PlaySound()
  48. {
  49. if (mCor != null)
  50. {
  51. StopCoroutine(mCor);
  52. mCor = null;
  53. }
  54. if (delayPlayTime <= 0)
  55. {
  56. PlayUISound();
  57. }
  58. else
  59. {
  60. mCor = StartCoroutine(DelayPlaySound());
  61. }
  62. }
  63. IEnumerator DelayPlaySound()
  64. {
  65. yield return new WaitForSeconds(delayPlayTime);
  66. PlayUISound();
  67. }
  68. void PlayUISound()
  69. {
  70. if (!string.IsNullOrEmpty(soundName))
  71. {
  72. MusicMgr.Instance.PlayUISound(soundName, false);
  73. }
  74. else
  75. {
  76. if(trigger == Trigger.OnClick)
  77. MusicMgr.Instance.PlayUISound(CommonClickSound, false);
  78. }
  79. }
  80. }