colt1911 colt1911 - 6 months ago 52
Javascript Question

Level Timer- How to Create Time Limit in Unity?

How do I create a GUI script in Unity that will restart level at a certain amount of seconds, so the level is timed? For example at 30 seconds the level restarts or goes back to main menu.

Here is my Timer Script

Image

The level that I am on is marked as 0 in the build settings.
The Main Menu is a different number.

Answer

Stop using OnGUI and JavaScript/UnityScript. Use the new Unity UI and C#. Simply create a text and attach the text to the timerText slot, you will be able to see the timer counting from 0 to 30 or to any passed in value.

C#:

void Start()
{
    StartCoroutine(reloadTimer(30));
}

public Text timerText;

IEnumerator reloadTimer(float reloadTimeInSeconds)
{
    float counter = 0;

    while (counter < reloadTimeInSeconds)
    {
        counter += Time.deltaTime;
        timerText.text = counter.ToString();
        yield return null;
    }

    //Load new Scene
    SceneManager.LoadScene(0);
}

Make sure to include using UnityEngine.SceneManagement; and using UnityEngine.UI;

JavaScript:

public var timerText : UI.Text;

function Start () {
    reloadTimer(30);
}

function reloadTimer(reloadTimeInSeconds : float){
    var counter = 0;

    while (counter < reloadTimeInSeconds)
    {
        counter += Time.deltaTime;
        timerText.text = counter.ToString();
        yield;
    }

    //Load new Scene
    UnityEngine.SceneManagement.SceneManager.LoadScene(0);
}