[英]Ive made a slider that adjust the games volume in the main menu but the music reverts to normal when the scene is changed to the actual game?
how can i make it so changes i made in the main menu scene are carried over into the game scene?我如何才能使我在主菜单场景中所做的更改能够延续到游戏场景中?
below is the code i used for the music player.下面是我用于音乐播放器的代码。
// 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;
}
There are a few options有几个选项
Make the musicVolume
a static
so the value is "shared" between all instances of that class.将musicVolume
设为static
以便该值在该类的所有实例之间“共享”。
private static float musicVolume = 1.0f;
Or use DontDestroyOnLoad
to use allways the same component in all Scenes.或者使用DontDestroyOnLoad
在所有场景中使用始终相同的组件。
private void Awake () { DontDestroyOnLoad(gameObject); }
but than make sure you have that object with this component only included once in the first Scene so you don't have multiple objects later.但要确保该对象与此组件仅包含在第一个场景中一次,因此以后不会有多个对象。
you could use a ScriptableObject for this kind of settings.您可以将ScriptableObject用于此类设置。 This is more powerful and flexible and "orthodox" than using a static
value.这比使用static
值更强大、更灵活和“正统”。
It is a bit more complicated to get into this but it is worth it.进入这个有点复杂,但这是值得的。 Here is a tutorial .这是一个教程。
[CreateAssetMenu(fileName = "New SettingsAsset", menuName = "Example/SettingsAsset"] public class SettingsAsset : ScriptableObject { public float musicVolume = 1.0f; }
create one SetttingsAsset by right click in the ProjectView
(Assets) and in the menu find Example
-> SettingsAsset
通过在ProjectView
(Assets) 中右键单击并在菜单中找到Example
-> SettingsAsset
创建一个ProjectView
and than reference these settings in all Scenes and components wherever needed.然后在需要的所有场景和组件中引用这些设置。 In this case eg在这种情况下,例如
// 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; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.