- Home /
How do I make music continue through certain scenes
I am still fairly new to Unity and Javascript Development and I am working on a 2d platformer with a fully functioning main menu. At this moment in time, the main menu consists of multiple scenes including settings, credits and a start game button that takes you to a scene called testlevel.
I want my main menu to have music separate to that of my credits screen and that of the game scene however I am struggling to code it to work. In the MainMenu scene there is a camera that hosts a script named MusicGenerator that reads as follows -
pragma strict
ar music : GameObject;
function Start () {
var G : GameObject = GameObject.FindGameObjectWithTag("GameController");
if(!G) {
Instantiate(music, Vector3.zero, Quaternion.identity);
}
}
there is prefab connected to this script named music. This prefab has another script attached that reads as follows
pragma strict
function Start () {
DontDestroyOnLoad(gameObject);
}
Of course there is a music source attached to this prefab with an audio file playing at all times.
When these scripts work together they basically search for a prefab named music in the current scene. If no such prefab can be found it creates a new instance. If it finds one that is already there, it will create a new instance of the prefab and continue the music. However what I want is for the script to be able to be altered so that different music can be played and continued throughout different scenes
Answer by Josh1231 · Dec 31, 2014 at 12:10 AM
you'd have to have a new variable with an array of all of the sound clips:
public AudioClip[] songs;
you would then change the audio clip:
AudioSource as = G.GetComponent();
as.clip = songs[Random.Range(0,songs.Length)];
as.Play();
you can also wait until the song finishes:
AudioSource as = G.GetComponent();
yield WaitForSeconds(as.clip.Length - as.time); //This is the only JS line here, the rest is C#
as.clip = songs[Random.Range(0,songs.Length)];
as.Play();
or, alternatively:
public GameObject[] songs;
then you would delete the original object:
AudioSource as = G.GetComponent();
Destroy(G) //you can wait until song end with Destroy(G,as.clip.Length - as.time);
yield WaitForSeconds(as.clip.Length - as.time);
Instantiate(songs[Random.Range(0,songs.Length)],Vector3.zero,Quaternion.identity);
I'd recommend the one at the top, because you don't lose the original object, and you wouldn't need something like garbage collecting because you instantiated too much objects.
yes, and you want to make sure that the object with the song has don't destroy on load
@ske66 if the answer helped, make sure you +1 and mark as correct (a way of saying thanks and showing appreciation)