- Home /
Make a command run only once
Ok so i just started using unity and i am a noob at it. I know a decent amount of javascript but unityscript is still new to me. What i want to do is only run a command once even if the scene is reloaded. What i really want to do is have some background music in my game and i figured out how to do it but when i reload the scene the music overlaps (basically runs the command again) i have dontdestroyonload on a gameobject but it still doesn't work (still repeats) here is my code and i want javascript only:
#pragma strict
static var currentScore : int = 0;
var offsetY : float = 40;
var sizeX : float = 80;
var sizeY : float = 25;
DontDestroyOnLoad(this.gameObject);
audio.Play();
function Start()
{
currentScore = 0;
}
function OnGUI()
{
GUI.Box(new Rect(Screen.width/2-sizeX/2, offsetY, sizeX, sizeY), "Score: " + currentScore);
}
Plz help me and remember javascript only
This is a good candidate for the static keyword.
You need a Audio class of its own. $$anonymous$$ake this static as you only want one and you want it to persist.
Alternatively your audio setup class can check for the presence of an existing audio class instance.
Answer by Blaque · Feb 08, 2015 at 08:55 PM
Do operations out of functions is a bad idea, you can try using PlayerPrefs
function Start()
{
if (PlayerPrefs.GetInt("PlayedAudio", 0) == 0){
audio.Play();
PlayerPrefs.SetInt("PlayedAudio", 1);
}
currentScore = 0;
}
Information stored with playerPrefs are permanent, anyway if you want to reload the music you have just to set PlayedAudio to 0
Your answer
Follow this Question
Related Questions
How do I stop footstep sound from playing when I release 'w'? 1 Answer
How I can prevent music from stopping after changing a scene? 3 Answers
Playing Music Problem. 2 Answers
Why sound doesn't stop? 2 Answers
Enemy following Player in range 2 Answers