Home > Enterprise >  How can I access a scene from another scenes script
How can I access a scene from another scenes script

Time:05-08

I have a homework assigned and I need the make a sound and music volume thing and I want it to be used in other scripts too. What I mean is : enter image description here

So when I drag the slider value to 0.2 for example I want the audio source on the other scene to have volume 0.2, but I have no idea how thats made. Thanks. (I only have a plan but no code) Also does anyone know why does it take forever to load when you save a script and go to unity: enter image description here

CodePudding user response:

To do this you would write a singleton script AudioManager that is set to DontDestroyOnLoad

It's just a script holding your AudioSources and that doesn't get destroy when you switch scenes.


Something like this

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

Then you can alter your audio sources as you wish, they won't get destroy after switching scene.

CodePudding user response:

A great way to do this is to use static variables that are actually defined for the class And can hold variables between scenes.

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

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

To call them, you just need to write the full name of the class before the variable name.

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

Remember that these are class variables will set in all instances of the same class. Also if you want your variables to be loaded after re-running the game. I suggest using PlayerPrefs for saving them.

  • Related