【Unity】简易游戏声音管理 AudioManager

下面是我游戏简易的声音管理,记录一下
包括背景音乐,音效,震动管理,其中音乐和音效可以设置声音大小并存储记录

using System.Collections.Generic;
using UnityEngine;

public class AudioManager : Singleton<AudioManager>
{

    private static string VIBRATE_STATE = "VIBRATE_STATE";
    private static string MUSIC_VOLUME = "MUSIC_VOLUME";
    private static string SOUND_VOLUME = "SOUND_VOLUME";

    public bool IsVibrate => vibrate;
    private bool vibrate;

    public float MusicVolume => musicVolume;
    private float musicVolume;

    public float SoundVolume => soundVolume;
    private float soundVolume;


    private Dictionary<string, AudioSource> soundDic = new Dictionary<string, AudioSource>();

    private void Start()
    {
        vibrate = PlayerPrefs.GetFloat(VIBRATE_STATE, 1) == 1;
        musicVolume = PlayerPrefs.GetFloat(MUSIC_VOLUME, 1f);
        soundVolume = PlayerPrefs.GetFloat(SOUND_VOLUME, 1f);

        PlayMusic("BGM");

    }


    public string soundTestName = "logo";
    [ContextMenu("测试播放声音")]
    public void TestPlay()
    {
        PlaySound(soundTestName);
    }


    /// <summary>
    /// 震动
    /// </summary>
    /// <param name="isStrong"></param>
    public void Vibrate(bool isStrong = false)
    {
        if (IsVibrate)
        {
            Utils.CallVibrate(isStrong ? 1520 : 1519);
        }
    }


    public void SetVibrateState(bool state)
    {
        vibrate = state;
        PlayerPrefs.SetInt(VIBRATE_STATE, vibrate ? 1 : 0);
    }

    public void SetMusicVolume(float volume)
    {
        musicVolume = volume;
        PlayerPrefs.SetFloat(MUSIC_VOLUME, volume);
    }

    public void SetSoundVolume(float volume)
    {
        soundVolume = volume;
        PlayerPrefs.SetFloat(SOUND_VOLUME, volume);
    }



    public void PlaySound(string name)
    {
        AudioSource audioSource = GetAudioSource(name);
        audioSource.volume = SoundVolume;
        audioSource.Play();
    }


    public void PlayMusic(string name)
    {
        AudioSource audioSource = GetAudioSource(name);
        audioSource.volume = MusicVolume;
        audioSource.loop = true;
        audioSource.Play();
    }


    private AudioSource GetAudioSource(string sound)
    {
        AudioSource audioSource = null;
        if(soundDic.TryGetValue(sound, out audioSource))
        {
            return audioSource;
        }
        GameObject go = new GameObject(sound);
        go.transform.SetParent(transform);
        audioSource = go.AddComponent<AudioSource>();

        string path = string.Format("Sounds/{0}", sound);
        var soundFile = Resources.Load(path);
        AudioClip clip = soundFile as AudioClip;
        audioSource.clip = clip;
        soundDic.Add(sound, audioSource);
        return audioSource;
    }


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值