Changing Music Volume = Calling a function in another script in another scene

Music plays in all scenes, but I can’t change the volume, except in the startup scene. I’m using the following JS to start the music in the startup screen of the game. The volume needs to be adjusted in the game’s setup scene. Just saying “audio.volume =” works here in the startup script, but does not work in the later setup scene. Obviously the compiler does not know which volume I want to change, and ignores my request. Wasn’t there a way to access, in this case, my function “MusicVolume” inside this script, which I named “BackgroundMusic”, from another JS in another scene? I just don’t know how to do this!

var backgroundMusic : AudioClip;

    audio.clip = backgroundMusic;
    audio.Play();
    
    function Start()
    {
    MusicVolume();
    //if(!PlayerPrefs.HasKey("MusicLevel")) { audio.volume = PlayerPrefs.GetFloat("MusicLevel");}
    }
    
    function MusicVolume()
    {
    if(!PlayerPrefs.HasKey("MusicLevel")) { audio.volume = PlayerPrefs.GetFloat("MusicLevel");}
    }

Given that it’s a global music player, you’ll probably want to make it a static thing, and make MusicVolume() a static function.

You must find the object at which the script is attached then access the script with GetComponent(BackgroundMusic). Supposing the object name is “Jukebox”, you can do the following:

    var juke = GameObject.Find("Jukebox"); // find the object
    juke.transform.GetComponent(BackgroundMusic).MusicVolume();

But if you want to allow volume control at any point of your game, add this slide control to your script BackgroundMusic.js - it will show the slider all the time:

private var curVolume: float;

function Start(){
  MusicVolume(); // set the initial volume from PlayerPrefs
  curVolume = audio.volume; // copy it to curVolume
}

function OnGUI(){ // this slider will be shown all the time in the screen
  curVolume = GUI.HorizontalSlider (Rect (25, 25, 100, 30), curVolume, 0.0, 1.0);
  audio.volume = curVolume;
}