unity——Prejct3——背景音乐
1.音乐数据结构类
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//音乐数据结构类
public class MusicData
{
//背景音乐 音效 开关
public bool musicOpen = true;
public bool soundOpen = true;
//背景音乐 音效 大小
public float musicValue = 0.2f;
public float soundValue = 0.2f;
}
2.数据管理类
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
// 数据管理类
public class GameDataMgr
{
private static GameDataMgr instance = new GameDataMgr();
public static GameDataMgr Instance => instance;
//音乐 音效 相关数据
public MusicData musicData;
private GameDataMgr()
{
//初始化默认数据 如果第一次进入游戏 Json会直接默认数据
musicData = JsonMgr.Instance.LoadData<MusicData>("MusicData");
}
/// <summary>
/// 存储音乐 音效数据
/// </summary>
public void SaveMusicData()
{
JsonMgr.Instance.SaveData(musicData, "MusicData");
}
}
3.真实背景音乐类
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BKMusic : MonoBehaviour
{
private static BKMusic instance;
public static BKMusic Instance => instance;
private AudioSource bkSource;
// Start is called before the first frame update
void Awake()
{
instance = this;
bkSource = this.GetComponent<AudioSource>();
//通过真正的音乐数据来设置背景音乐的数据
MusicData data = JsonMgr.Instance.LoadData<MusicData>("MusicData");
SetIsOpen(data.musicOpen);
ChangeValue(data.musicValue);
}
//开关背景音乐
public void SetIsOpen(bool isOpen)
{
bkSource.mute = !isOpen;
}
//调整背景音乐大小
public void ChangeValue(float v)
{
bkSource.volume = v;
}
}