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

2023-11-23  本文已影响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);
    }
}
上一篇 下一篇

猜你喜欢

热点阅读