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

How can I access a scene from another scenes script

我有一个家庭作业,我需要制作声音和音乐音量的东西,我也希望它能用在其他脚本中。 我的意思是 : enter image description here

因此,例如,当我将滑块值拖动到 0.2 时,我希望另一个场景的音频源的音量为 0.2,但我不知道这是怎么做到的。 谢谢。 (我只有计划,没有代码) 还有人知道为什么在保存脚本并统一时需要永远加载: enter image description here

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

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


像这样

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
        }
    }
}

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

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

public class AudioManager
{
    public static float MusicVolume = 1f;
    public static float SoundVolume = .5f;

    public void SetVolume(float value) => MusicVolume = value;
}

要调用它们,只需要在变量名前写上class的全称即可。

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

请记住,这些 class 变量将设置在相同 class 的所有实例中。此外,如果您希望在游戏 re-running 之后加载变量。我建议使用 PlayerPrefs 来保存它们。

好吧,我有很多事情要做,但是好吧,你们发给我的脚本,所以如果我把它放在音频游戏对象上,我仍然不知道如何从 1 更改参数其他人的场景(我是初学者,我 13 岁,所以我可能不明白音频 ATM 是什么,但是是的。)

简而言之,我需要这个:

Scene1.findgameobject.name = blah blah = 菜单中的音频游戏对象