C# 我制作了一个滑块,可以调整主菜单中的游戏音量,但当场景更改为实际游戏时,音乐会恢复正常?
我如何才能使我在主菜单场景中所做的更改被带入游戏场景 下面是我用于音乐播放器的代码C# 我制作了一个滑块,可以调整主菜单中的游戏音量,但当场景更改为实际游戏时,音乐会恢复正常?,c#,unity3d,C#,Unity3d,我如何才能使我在主菜单场景中所做的更改被带入游戏场景 下面是我用于音乐播放器的代码 // Reference to Audio Source component private AudioSource audioSrc; // Music volume variable that will be modified // by dragging slider knob private float musicVolume = 1f; // Use this for initialization
// Reference to Audio Source component
private AudioSource audioSrc;
// Music volume variable that will be modified
// by dragging slider knob
private float musicVolume = 1f;
// Use this for initialization
void Start()
{
// Assign Audio Source component to control it
audioSrc = GetComponent<AudioSource>();
}
// Update is called once per frame
void Update()
{
// Setting volume option of Audio Source to be equal to musicVolume
audioSrc.volume = musicVolume;
}
// Method that is called by slider game object
// This method takes vol value passed by slider
// and sets it as musicValue
public void SetVolume(float vol)
{
musicVolume = vol;
}
//对音频源组件的引用
私人音频源audioSrc;
//将被修改的音乐音量变量
//通过拖动滑块旋钮
私人浮动音乐音量=1f;
//用于初始化
void Start()
{
//指定音频源组件来控制它
audioSrc=GetComponent();
}
//每帧调用一次更新
无效更新()
{
//将音频源的音量选项设置为等于musicVolume
audioSrc.volume=音乐音量;
}
//由slider游戏对象调用的方法
//此方法采用滑块传递的vol值
//并将其设置为musicValue
公共空间设置体积(浮动体积)
{
音乐音量=音量;
}
有几个选项
musicVolume
astatic
,使该值在该类的所有实例之间“共享”
private static float musicVolume = 1.0f;
private void Awake ()
{
DontDestroyOnLoad(gameObject);
}
但是,请确保在第一个场景中仅包含一次包含此组件的对象,以便以后不会有多个对象静态值更强大、更灵活、更“正统”
这有点复杂,但值得一试。这是一本书
右键单击项目视图
(资产)并在菜单中查找示例
->设置集
然后,在需要时在所有场景和组件中引用这些设置。在这种情况下,例如
// Reference in the inspector
public SettingsAsset settings;
// ...
// Though I doubt you would need to do this in Update
// If you only change the settings from within a separate settings scene
// you probably should do this only once
private void Update()
{
audioSrc.volume = settings.musicVolume;
}
你在每个场景中都有这个脚本的新实例吗?
// Reference in the inspector
public SettingsAsset settings;
// ...
// Though I doubt you would need to do this in Update
// If you only change the settings from within a separate settings scene
// you probably should do this only once
private void Update()
{
audioSrc.volume = settings.musicVolume;
}