- Home /
Change level after ''X'' seconds
Hello can some one help me, I am devloping a game in which you have to visit diferent places in a ''X'' amount of time I am using this code but I don't know why it dosen work...
function Start(){
yield WaitForSeconds(30);
Application.LoadLevel(1);
yield return new WaitForSeconds(30); Application.LoadLevel(2);
}
Answer by SentreStage · Aug 04, 2011 at 03:02 AM
I haven't tested this code, but I'm at least 90% sure this would be the right way to do it.
//Level you want to load, this can be adjusted in the inspector
var levelIndexToLoad : int = 1
var timeToWait : float = 30.0f;
function Start(){
LoadLevelAfterTime();
}
function LoadLevelAfterTime(){
yield WaitForSeconds(timeToWait);
Application.LoadLevel(levelIndexToLoad);
levelIndexToLoad++;
}
Now the reason you want to do it this way is because the Start(), Update(), and FixedUpdate() functions can NOT be ran as a coroutine. And inorder to use the WaitForSeconds() function it must be called within a coroutine. Let me know if this script works for you now. All you should need to do is attach it to an object in the scene, select the time to wait, and the level index in the inspector pane of that object, and after the set amount of time it should load that level without any problems. You would only need one copy of this per scene that you want to achieve this effect on.
Answer by YikYikHeiHei · Aug 04, 2011 at 04:00 AM
use DontDestroyOnLoad() to load any level And this script is put in a level is load once
static var loadAlevel = 1;
function Awake()
{
DontDestroyOnLoad(this);
StartWait ();
}
function StartWait ()
{
yield WaitForSeconds(30);
Application.LoadLevel(loadAlevel);
loadAlevel ++;
}
The only problem I see with that is that if he did it that way then he would have to ensure that he loaded each level up in specific order into the build settings. Also, if he has 4 levels, (0, 1, 2, 3) then when he gets to the last level and the timer runs out, it will throw an error because it will try to load the next level which doesn't exist.
Also, there might be a time when he would like to jump back to a previous level after the timer runs out, like say, to a $$anonymous$$igame level or something.
Add this in StartWait()
var maxLevel = 3
if (loadAlevel == maxLevel)
{
loadAlevel = 0;
}