美文网首页
Unity中,激活时播放一次音效或激活期间持续播放某音效

Unity中,激活时播放一次音效或激活期间持续播放某音效

作者: 全新的饭 | 来源:发表于2023-11-23 17:49 被阅读0次

    功能说明如题。
    使用方式:把该脚本组件添加到相应GO上即可。
    PlaySoundWhenEnable.cs

    using System.Collections;
    using Audio;
    using UnityEngine;
    public class PlaySoundWhenEnable : MonoBehaviour
    {
        [SerializeField]
        private AudioClip _clip;
        [SerializeField]
        private bool _isLoop = false;
    
        private IEnumerator _playSoundCoroutine;
    
        private void OnEnable()
        {
            StartPlaySound();
        }
        private void OnDisable()
        {
            StopPlaySound();
        }
    
        private void StartPlaySound()
        {
            if (_isLoop)
            {
                _playSoundCoroutine = PlaySoundCoroutine();
                MonoSys.Instance.StartCoroutine(_playSoundCoroutine);
            }
            else
            {
                PlaySound();
            }
    
            IEnumerator PlaySoundCoroutine()
            {
                var waitForSeconds = new WaitForSeconds(_clip.length);
                while (true)
                {
                    PlaySound();
                    yield return waitForSeconds;
                }
            }
    
            void PlaySound()
            {
                AudioSys.Instance.PlaySound(_clip);
            }
        }
        private void StopPlaySound()
        {
            MonoSys.Instance.DestroyCoroutine(ref _playSoundCoroutine);
        }
    }
    

    相关文章

      网友评论

          本文标题:Unity中,激活时播放一次音效或激活期间持续播放某音效

          本文链接:https://www.haomeiwen.com/subject/wajgwdtx.html