- Home /
AudioSource in Update
Hey guys,
I have different background music clips that should play even if I restart the game.
For that purpose I have created a Script attached on a gameObject that only plays the music.
private var player : GameObject;
var mg : AudioClip;
var def : AudioClip;
function Awake(){
DontDestroyOnLoad(this.gameObject);
if (FindObjectsOfType(GetType()).Length > 1){
Destroy(gameObject); //Avoid duplicate on scene restart
}
}
function Start () {
player = GameObject.Find("Player");
}
function Update () {
if(PlayerPrefs.GetInt("TimesPlayed") >= PlayerPrefs.GetInt("OverallScore")){
GetComponent.<AudioSource>().clip = mg;
GetComponent.<AudioSource>().Play();
}
if(player.transform.GetChild(0).gameObject.name == "CubeDefault"){
GetComponent.<AudioSource>().clip = def;
GetComponent.<AudioSource>().Play();
}
}
The problem is that the specified clip is called every frame since it is in the update function, but it needs to be in this function, because
at Runtime the music can change,
the script will never be destroyed and so I can not put this code to the start/awake function as they read the content only once.
The solution would be some kind of "if" that change their values to call
GetComponent.<AudioSource>().Play();
only once, but how can I do this?
Thanks
ins$$anonymous$$d of checking TimesPlayed every frame, you could check it when you change it. that will result in just one call to your AudioSource. I'm not exactly sure what's going on with the CubesDefault name, but if that is something that does not exist from the beginning, call the code when the name appears.
General rule: Ins$$anonymous$$d of checking all the time, execute code in change directly.
Your answer
Follow this Question
Related Questions
Can I make an audio source play its clip starting at a time in the clip besides the beginning? 1 Answer
Audio Clip Array within an Audio Source Array 0 Answers
Looping an audio while holding "shift key" 1 Answer
Breathing volume increases as player gets more tired 0 Answers
[SOLVED] audio background music making buzzing sound 2 Answers