SoundEvent.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. using System;
  2. using UnityEngine;
  3. namespace Xft
  4. {
  5. public class SoundEvent : XftEvent
  6. {
  7. public SoundEvent(XftEventComponent owner) : base(XEventType.Sound, owner)
  8. {
  9. }
  10. protected AudioSource PlaySound(AudioClip clip, float volume, float pitch)
  11. {
  12. volume *= GlobalConfig.SoundVolume;
  13. if (clip != null)
  14. {
  15. if (SoundEvent.m_Listener == null)
  16. {
  17. SoundEvent.m_Listener = (UnityEngine.Object.FindObjectOfType(typeof(AudioListener)) as AudioListener);
  18. if (SoundEvent.m_Listener == null)
  19. {
  20. Camera camera = Camera.main;
  21. if (camera == null)
  22. {
  23. camera = (UnityEngine.Object.FindObjectOfType(typeof(Camera)) as Camera);
  24. }
  25. if (camera != null)
  26. {
  27. SoundEvent.m_Listener = camera.gameObject.AddComponent<AudioListener>();
  28. }
  29. }
  30. }
  31. if (SoundEvent.m_Listener != null)
  32. {
  33. AudioSource audioSource = SoundEvent.m_Listener.GetComponent<AudioSource>();
  34. if (audioSource == null)
  35. {
  36. audioSource = SoundEvent.m_Listener.gameObject.AddComponent<AudioSource>();
  37. }
  38. audioSource.pitch = pitch;
  39. audioSource.loop = this.m_owner.IsSoundLoop;
  40. if (!this.m_owner.IsSoundLoop)
  41. {
  42. audioSource.PlayOneShot(clip, volume);
  43. }
  44. else
  45. {
  46. audioSource.clip = clip;
  47. audioSource.volume = volume;
  48. audioSource.Play();
  49. }
  50. return audioSource;
  51. }
  52. }
  53. return null;
  54. }
  55. public override void Reset()
  56. {
  57. base.Reset();
  58. if (SoundEvent.m_Listener != null && SoundEvent.m_Listener.GetComponent<AudioSource>() != null && this.m_owner.IsSoundLoop)
  59. {
  60. SoundEvent.m_Listener.GetComponent<AudioSource>().Stop();
  61. }
  62. }
  63. public override void OnBegin()
  64. {
  65. base.OnBegin();
  66. this.PlaySound(this.m_owner.Clip, this.m_owner.Volume, this.m_owner.Pitch);
  67. }
  68. private static AudioListener m_Listener;
  69. }
  70. }