MusicManager.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. using System.Collections;
  2. using UnityEngine;
  3. using GFGGame.Launcher;
  4. using YooAsset;
  5. namespace GFGGame
  6. {
  7. public class MusicManager : SingletonMonoBase<MusicManager>
  8. {
  9. private AudioSource player;
  10. private string currentName;
  11. private AssetOperationHandle handle;
  12. private Coroutine coroutine;
  13. private bool _isOn = true;
  14. public bool isOn
  15. {
  16. get
  17. {
  18. return _isOn;
  19. }
  20. set
  21. {
  22. if(_isOn != value)
  23. {
  24. _isOn = value;
  25. if(_isOn)
  26. {
  27. if(currentName != null)
  28. {
  29. PlayCroutine(currentName, true);
  30. }
  31. }
  32. else
  33. {
  34. Stop();
  35. }
  36. LocalCache.SetBool(LauncherConfig.MUSIC_KEY, _isOn);
  37. }
  38. }
  39. }
  40. private void Awake()
  41. {
  42. player = this.gameObject.AddComponent<AudioSource>();
  43. player.loop = true;
  44. }
  45. private void Start()
  46. {
  47. }
  48. private void Update()
  49. {
  50. }
  51. public void PlayCroutine(string path, bool must = false)
  52. {
  53. if(currentName != path || must)
  54. {
  55. currentName = path;
  56. if(coroutine != null)
  57. {
  58. StopCoroutine(coroutine);
  59. }
  60. handle?.Release();
  61. if (_isOn)
  62. {
  63. coroutine = StartCoroutine(Play(path));
  64. }
  65. }
  66. }
  67. private IEnumerator Play(string path)
  68. {
  69. //AudioClip clip = GFGAsset.Load<AudioClip>(path);
  70. handle = YooAssets.LoadAssetAsync<AudioClip>(path);
  71. yield return handle;
  72. player.clip = handle.AssetObject as AudioClip;
  73. player.Play();
  74. }
  75. public float GetSoundTime()
  76. {
  77. if (player.clip != null)
  78. {
  79. return player.clip.length;
  80. }
  81. return 0;
  82. }
  83. public void Pause()
  84. {
  85. player.Pause();
  86. }
  87. public void UnPause()
  88. {
  89. player.UnPause();
  90. }
  91. public void Stop()
  92. {
  93. handle.Release();
  94. player.Stop();
  95. }
  96. }
  97. }