BGMObject.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using DG.Tweening;
  5. [RequireComponent(typeof(AudioSource))]
  6. public class BGMObject : MonoBehaviour
  7. {
  8. public AudioSource _audio { get; set; }
  9. public bool isPlaying { get; set; } = false;
  10. bool isFading { get; set; } = false;
  11. private void Start()
  12. {
  13. }
  14. public void StopPlayBGM()
  15. {
  16. _audio = GetComponent<AudioSource>();
  17. _audio.Stop();
  18. _audio.clip = null;
  19. isPlaying = false;
  20. }
  21. public void StartPlayBGM(AudioClip clip)
  22. {
  23. _audio = GetComponent<AudioSource>();
  24. if (clip != null)
  25. {
  26. _audio.clip = clip;
  27. }
  28. if (ContinuousController.instance != null)
  29. {
  30. ContinuousController.instance.ChangeBGMVolume(_audio);
  31. }
  32. _audio.Play();
  33. isPlaying = true;
  34. }
  35. private void Update()
  36. {
  37. if (ContinuousController.instance != null)
  38. {
  39. if (_audio != null && isPlaying && !isFading)
  40. {
  41. ContinuousController.instance.ChangeBGMVolume(_audio);
  42. }
  43. }
  44. }
  45. public IEnumerator FadeOut(float duration)
  46. {
  47. _audio = GetComponent<AudioSource>();
  48. bool end = false;
  49. isFading = true;
  50. var sequence = DOTween.Sequence();
  51. sequence
  52. .Append(DOTween.To(() => _audio.volume, (value) => _audio.volume = value, 0, duration))
  53. .AppendCallback(() => end = true);
  54. sequence.Play();
  55. yield return new WaitWhile(() => !end);
  56. isPlaying = false;
  57. isFading = false;
  58. }
  59. }