我如何从另一个场景脚本访问一个场景



我有一个作业分配,我需要做一个声音和音乐音量的东西,我希望它在其他脚本中使用。我的意思是:输入图片描述

因此,当我将滑块值拖动到0.2时,例如,我希望另一个场景中的音频源具有0.2的音量,但我不知道这是如何制作的。谢谢。(我只有一个计划,但没有代码)还有,有人知道为什么当你保存脚本并进入unity时,加载时间总是很长吗?输入图片描述

这样做的一个好方法是使用static变量,这些变量实际上是为类定义的,并且可以在场景之间保存变量。

public class AudioManager
{
public static float MusicVolume = 1f;
public static float SoundVolume = .5f;
public void SetVolume(float value) => MusicVolume = value;
}

要调用它们,只需要在变量名之前写类的全名。

public class Player : MonoBehaviour
{
public AudioClip AudioClip;
public void Shot()
{
AudioSource.PlayClipAtPoint(AudioClip, transform.position, AudioManager.SoundVolume);
}
}

请记住,这些类变量将在同一个类的所有实例中设置。此外,如果你希望你的变量加载后重新运行游戏。我建议使用PlayerPrefs来保存它们。

为此,您需要编写一个单例脚本AudioManager设置为DontDestroyOnLoad

它只是一个保存AudioSources的脚本,当你切换场景时它不会被破坏。


像这样的

public class AudioManager : MonoBehaviour
{
private static AudioManager instance;
[Header("AudioSources")]
[SerializeField] private AudioSource musicSource;
[SerializeField] private AudioSource soundSource;
private void Awake()
{
// If you have AudioManager in every scene, you want to only keep the main one (the first one)
if (instance != null && instance != this) 
{
Destroy(gameObject);
}
else 
{
instance = this;
DontDestroyOnLoad(this); // This line will tell Unity to keep this gameobject when switching scenes
}
}
}

然后你可以随意改变你的音频源,它们不会在切换场景后被破坏。

很好,我有很多事情要做,但好吧,你们发给我的脚本,所以如果我把它放在音频Gameobject上,我仍然不知道如何从一个场景改变参数到其他场景(我是一个初学者,我13岁,所以我可能不知道音频ATM是什么,但是的)

简而言之,我需要这个:

Scene1.findgameobject.name = blah blah = audiogameobject in menu

相关内容

最新更新