【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;
    }


}

猜你喜欢

转载自blog.csdn.net/qq_41789645/article/details/142640523