/// <summary> /// 播放音效 /// </summary> /// <param name="abName">音效的ab名字</param> /// <param name="loop">是否循环</param> /// <param name="isFade">是否淡化背景音乐</param> /// <returns> 返回音效id</returns> public void PlaySound(int id, bool loop = false, Action action = null, bool isFade = true) { if (CurrentSoundId >= 39 && CurrentSoundId <= 45) { return; } StopSound(); soundID++; var audioSource = gameObject.AddComponent <AudioSource>(); Debug.Log(GetDubbingName(id)[0] + "----" + GetDubbingName(id)[1]); AudioClip audioClip = ResourceManager.GetInstance.LoadAudioClip(GetDubbingName(id)[0], GetDubbingName(id)[1]); //动态添加音效 audioSource.clip = audioClip; audioSource.loop = loop; audioSource.volume = volume; audioSource.Play(); CurrentSoundId = id; SoundDictionary.Add(soundID, audioSource); if (isFade) { foreach (var item in SoundDictionary) { if (item.Key != soundID) { item.Value.DOFade(0.2f, 1f); } } CurrentMusic.DOFade(0.2f, 2); } StartCoroutine(PlaySoundEndDestroy(audioSource, soundID, action, isFade)); }
/// <summary> /// 音乐自动销毁 /// </summary> /// <param name="audioclip"></param> /// <param name="soundID"></param> /// <returns></returns> private IEnumerator PlaySoundEndDestroy(AudioSource audioclip, int soundID, Action action, bool isFade) { yield return(new WaitForSeconds(audioclip.clip.length + 1)); StopSound(soundID); if (isFade) { foreach (var item in SoundDictionary) { item.Value.DOFade(volume, 0.2f); } CurrentMusic.DOFade(volume, 0.2f); } if (action != null) { action(); } }