Can't make a good script for this. Help!

Hey everyone. I’ve been struggling to write a script that cooperates and does this: I have an audio source object that is supposed to play background music during the game. However, it is not supposed to play the music on certain levels. I already have a script that prevents the object from being destroyed when a new level is loaded. It also needs to be able to change the music it is playing when another script access it. I’ve written some pseudocode which I think is the way it should work. Please correct me if my logic is flawed and if you know of a better and/or easier way to do this please tell me. Also, let me know if anything is unclear or could be worded better and I’ll fix it. Thanks!

var levelsCan = an array with int representing the levels audio can play in
var levelsCant = an array with int representing the levels audio cant play in
var music1 : AudioClip;
var music2 : AudioClip;
var music3 : AudioClip;
//Allow in the script for more of the music variables. There are only three right now, but
//that will change in the future.
static var clipToPlay : int = 1; //Needs to be accessed from other scripts

function Update () {

	var level = get the number of the level that is currently running;
	search through levelsCan.
	If a number in levelsCan == level){
		if(clipToPlay == 1){
			audio.clip = music1;
		}
		else if(clipToPlay == 2){
			audio.clip = music2;
		}
		else if(clipToPlay == 3){
			audio.clip = music3;
		}
		//etc.
	}
	If level !== a number in levelsCan{
		audio.Stop();
	}
	

}
  1. Use an array, not separate variables for your audio clips.
  2. Your array index is now equal to your level, so there is no longer any need for your lengthy if->then->else or other tracking values. (which should be a switch statement anyhow). You can create a dummy audioclip that’s 1 second of nothing and assign it to the levels intended to have no music.
  3. Only switch music when you switch levels, or intend to switch music. Don’t do it every frame in Update().