- Home /
Make game pause on world enter
Hello, I'm new to Unity and C#, well basically scripting in general. So far I've created a little menu that, if I press on New Game, will load the tutorial world. But I want to set the Time.timeScale to 0 directly when the player enters the tutorial world.
My question: How do I make that happen?
Thank you.
Answer by Flynn · Jan 18, 2013 at 07:55 PM
Theoretically, setting timesScale to 0 right when you press the New Game button would work (unless you have some kind of crazy cool animation going on), however, if that is not an option, you can try adding this to your C# class:
public void OnLevelWasLoaded(int level)
{
if (level == YOUR_TUTORIAL_SCENE_NUMBER_HERE)
{
Time.timeScale = 0;
}
}
If you need to wait a few seconds after the scene has loaded (to get the ball rolling), then you can do one of the following:
ONE:
public void OnLevelWasLoaded(int level)
{
//Directly call a Coroutine, allowing you to yield for a number of seconds:
//(Coroutines are functions that can are excecuted "simultaneously" to other functions (when they yield, other functions continue excecution)
//This allows you to program in delay, without stopping the rest of your game
if (level == YOUR_TUTORIAL_SCENE_NUMBER_HERE)
{
StartCoroutine(OnLevelWasLoaded_Coroutine(level));
}
}
public IEnumerator OnLevelWasLoaded_Coroutine(int level)
{
yield return new WaitForSeconds(10);
//yield return yields until the following statement (which is in this case new WaitForSeconds()) returns.
//new WaitForSeconds() causes a pause of the given amount of seconds before returning.
}
Or, TWO:
//Unity automatically sees that this is an IENumerator, and starts it as a coroutine without you having to. This is cleaner code, but a bit slower, as we check if this was the correct scene AFTER the coroutine is started, instead of BEFORE.
public IENumerator OnLevelWasLoaded(int level)
{
if (level == YOUR_TUTORIAL_SCENE_NUMBER_HERE)
{
yield return new WaitForSeconds(10);
StartCoroutine(OnLevelWasLoaded_Coroutine(level));
}
}
OnLevelWasLoaded: http://docs.unity3d.com/Documentation/ScriptReference/MonoBehaviour.OnLevelWasLoaded.html Unity C# Coroutines: http://www.blog.silentkraken.com/2010/01/23/coroutines-in-unity3d-c-version/
And how would I put a timer on this? Let's say I want to explain the player something, and then let the message box dissapear, and start time again. Though I'm probably thinking of adding a button. Where that if the player would click on it, it sets the Time.timeScale = 1.
You can use http://stackoverflow.com/questions/1382597/javas-system-currenttimemillis-or-cs-environment-tickcount to measure the flow of time, ins$$anonymous$$d of Time.time for your GUI animations : D
Your answer