可能写的不太好
1.Start场景中新建一个空物体挂在音乐,挂在脚本
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DontDestoryAudio : MonoBehaviour
{
public static DontDestoryAudio instance;
private void Awake()
{
if (instance == null)
{
instance = this;
}
else
{
if (instance != this)
{
Destroy(gameObject);
}
}
DontDestroyOnLoad(this);
}
}
2.Start场景中,新建空物体,挂在脚本
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
///
/// 挂在Setting面板中的空物体上,用于获取slider的值,将其复制给场景中的Audio上
///
public class SetStartAudioVolumeValue : MonoBehaviour
{
private GameObject audioSlider1;//背景音乐slider
private GameObject audio;//挂在着背景音乐
private GameObject audioSlider2;//音效slider
private void Start()
{
audioSlider1 = GameObject.Find("YinYueSlider");//找到背景音乐滑动条
audio = GameObject.Find("Audio");//找到背景音乐
audioSlider2 = GameObject.Find("YinXiaoSlider");//找到音效滑动条
//如果不是从运行开始进入的start场景,就可能在主场景中修改过音量的大小,所以这时开始场景中的slider和audio大小都要等于修改后的音量值
if (PlayerPrefs.GetFloat("AudioValue1") != 1)
{
GameObject.Find("Audio").GetComponent<AudioSource>().volume = PlayerPrefs.GetFloat("AudioValue1");
audioSlider1.GetComponent<Slider>().value = PlayerPrefs.GetFloat("AudioValue1");
}
if (PlayerPrefs.GetFloat("AudioValue2") != 1)
{
audioSlider2.GetComponent<Slider>().value = PlayerPrefs.GetFloat("AudioValue2");
}
}
private void Update()
{
//使audio的大小总是=slider的大小
GameObject.Find("Audio").GetComponent<AudioSource>().volume = audioSlider1.GetComponent<Slider>().value;
//将audio的值存储起来
PlayerPrefs.SetFloat("AudioValue1", GameObject.Find("Audio").GetComponent<AudioSource>().volume);
PlayerPrefs.SetFloat("AudioValue2", audioSlider2.GetComponent <Slider>().value);
}
}
3.Main场景中挂在脚本
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class SetMainSceneAudioSet : MonoBehaviour
{
private GameObject audioSlider1;
private GameObject audio;
private GameObject audioSlider2;
private GameObject audioCamera;
private void Start()
{
audioSlider1 = GameObject.Find("YinYueSlider");
audio = GameObject.Find("Audio");
//刚开始slider的值为保存的AudioValue1
audioSlider1.GetComponent<Slider>().value = PlayerPrefs.GetFloat("AudioValue1");
audioSlider2 = GameObject.Find("YinXiaoSlider");
audioCamera = GameObject.Find("Main Camera1");
audioCamera.GetComponent<AudioSource>().volume = PlayerPrefs.GetFloat("AudioValue2");
audioSlider2.GetComponent<Slider>().value = audioCamera.GetComponent<AudioSource>().volume;
}
private void Update()
{
使audio的大小总是=slider的大小
audio.GetComponent<AudioSource>().volume = audioSlider1.GetComponent<Slider>().value;
//将audio的值存储起来
PlayerPrefs.SetFloat("AudioValue1", audio.GetComponent<AudioSource>().volume);
audioCamera.GetComponent<AudioSource>().volume = audioSlider2.GetComponent<Slider>().value;
PlayerPrefs.SetFloat("AudioValue2", audioCamera.GetComponent<AudioSource>().volume);
}
}
第一次写,有不对的地方欢迎批评指正(>~<)…