AudioAttach.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. using UnityEngine;
  2. using System.Collections;
  3. public class AudioAttach : MonoBehaviour
  4. {
  5. public static bool ProxyMode = false;
  6. public string clipName;
  7. public string clipPackageName;
  8. public bool repeat = false;
  9. public float delayTime = 0f;
  10. public float minInterval = 0f;
  11. public float maxInterval = 0f;
  12. public int countLimit = 0;
  13. /// <summary>
  14. /// 是否Awake时就播放
  15. /// </summary>
  16. public bool playOnAwake = false;
  17. /// <summary>
  18. /// 脚本删除之后声音继续播放
  19. /// </summary>
  20. public bool continuePlayAfterDestroy = false;
  21. float timeFromEnable = 0f;
  22. float nextInterval = 0f;
  23. int playCount = 0;
  24. /// <summary>
  25. /// 请求播放的声音序列号
  26. /// </summary>
  27. private ulong mClipOrder = 0;
  28. void Awake()
  29. {
  30. if (string.IsNullOrEmpty(clipName))
  31. {
  32. enabled = false;
  33. return;
  34. }
  35. clipName = clipName.Trim();
  36. clipPackageName = clipPackageName.Trim();
  37. if (playOnAwake)
  38. {
  39. CheckSound();
  40. }
  41. }
  42. void OnEnable()
  43. {
  44. timeFromEnable = 0f;
  45. timeFromEnable = 0f;
  46. nextInterval = 0f;
  47. playCount = 0;
  48. }
  49. void OnDisable()
  50. {
  51. ReleaseSound();
  52. }
  53. bool MultiPlay
  54. {
  55. get
  56. {
  57. return maxInterval > 0f || minInterval > 0f;
  58. }
  59. }
  60. // Update is called once per frame
  61. void Update()
  62. {
  63. CheckSound();
  64. }
  65. void CheckSound()
  66. {
  67. if (string.IsNullOrEmpty(clipName))
  68. return;
  69. if (timeFromEnable < delayTime)
  70. {
  71. timeFromEnable += Time.unscaledDeltaTime;
  72. return;
  73. }
  74. if (!MultiPlay)
  75. {
  76. if (playCount > 0)
  77. return;
  78. }
  79. else
  80. {
  81. if (countLimit > 0 && playCount >= countLimit)
  82. return;
  83. }
  84. if (nextInterval <= 0f)
  85. {
  86. PlaySound();
  87. playCount++;
  88. if (minInterval < maxInterval)
  89. nextInterval = Random.Range(minInterval, maxInterval);
  90. else if (minInterval > 0)
  91. nextInterval = minInterval;
  92. }
  93. else
  94. nextInterval -= Time.unscaledDeltaTime;
  95. }
  96. void PlaySound()
  97. {
  98. mClipOrder = AudioProxy.Instance.Add(clipName, clipPackageName, repeat && !MultiPlay);
  99. }
  100. void OnDestroy()
  101. {
  102. ReleaseSound();
  103. }
  104. void ReleaseSound()
  105. {
  106. if (!continuePlayAfterDestroy)
  107. {
  108. AudioProxy.Instance.Cancel(clipName);
  109. }
  110. }
  111. }