【U3D/簡單框架】5.音效管理模塊

自我介紹

廣東雙非一本的大三小白,計科專業,想在製作畢設前夯實基礎,畢設做出一款屬於自己的遊戲!

音效管理模塊

  • 知識點:AudioSource,List
  • 作用:統一管理音樂音效模塊

MusicMananger.cs

using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;

public class MusicManager : BaseSingleton<MusicManager>
{

    private AudioSource bgMusic = null;     // 唯一的背景音樂組件
    private float bgValue = 1;              // BGM的音樂大小

    private GameObject soundObj = null;
    private List<AudioSource> soundList = new List<AudioSource>();
    private float soundValue = 1;

    public MusicManager()
    {
        MonoManager.Instance().AddUpdateAction(Update);
    }

    private void Update()
    {
        for (int i = soundList.Count - 1; i >= 0; i++)
        {
            if (!soundList[i].isPlaying)
            {
                GameObject.Destroy(soundList[i]);
                soundList.RemoveAt(i);
            }
        }
    }

    public void PlayBgMusic(string name)
    {
        if (bgMusic == null)
        {
            GameObject obj = new GameObject("BgMusic");
            bgMusic = obj.AddComponent<AudioSource>();
        }
        // 異步加載背景音樂,加載完成後播放
        ResManager.Instance().LoadAsync<AudioClip>("path" + name, (clip) =>
        {
            bgMusic.clip = clip;
            bgMusic.volume = bgValue;
            bgMusic.loop = true;
            bgMusic.Play();
        });
    }

    public void ChangeBgMusicVolume(float v)
    {
        bgValue = v;
        if (bgMusic == null) return;
        bgMusic.volume = bgValue;
    }

    public void PauseBgMusic()
    {
        if (bgMusic == null) return;
        bgMusic.Pause();
    }

    public void StopBgMusic()
    {
        if (bgMusic == null) return;
        bgMusic.Stop();
    }

    public void PlaySound(string name, UnityAction<AudioSource> callback = null)
    {
        if (soundObj == null) soundObj = new GameObject("Sound");

        // 當音效資源異步加載結束後,在添加一個音效
        ResManager.Instance().LoadAsync<AudioClip>("path" + name, (clip) =>
        {
            AudioSource source = soundObj.AddComponent<AudioSource>();
            source.clip = clip;
            source.loop = false;
            source.volume = soundValue;
            source.Play();
            soundList.Add(source);
            callback?.Invoke(source);
        });
    }

    // 改變音效聲音大小
    public void ChangeSoundValue(float value)
    {
        soundValue = value;
        for (int i = 0; i < soundList.Count; i++)
            soundList[i].volume = value;
    }

    public void StopSound(AudioSource source)
    {
        if (soundList.Contains(source))
        {
            soundList.Remove(source);
            source.Stop();
            GameObject.Destroy(source);
        }
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章