- Home /
Trigger a scene with a timer
I have been looking for a timer that can trigger a scene when it hits 0 and there is no GUI please help unity 5.5
Answer by FlaSh-G · Jul 23, 2017 at 08:59 PM
A very easy (although not very robust) way to do this is the Invoke method. Like this:
void OnTriggerEnter() // For example
{
Invoke("ChangeScene", 10); // 10 seconds delay
}
void ChangeScene()
{
SceneManager.LoadScene("Some scene");
}
You can improve this code a bit by using nameof
:
void OnTriggerEnter() // For example
{
Invoke(nameof(ChangeScene), 10); // 10 seconds delay
}
void ChangeScene()
{
SceneManager.LoadScene("Some scene");
}
Answer by drakedane · Oct 12, 2017 at 07:55 PM
@ Diamonddoggames Not sure if the answer above worked for you; but I use something closer to what you described. This is only a temporary feature that I intend to remove, but once certain scenes are loaded, a timer starts. When timer reaches 0, the scene auto switches back to the original scene. The way it was designed, the countdown displays on-screen, but you don't have to do that.
Here is the code I use. I tried to strip out everything but the timer scripting.
public class Timer : MonoBehaviour
{
public string leveltoload;
private float timer = 10f;
private Text timerseconds;
void Start ()
{
timerseconds = GetComponent<Text>();
}
void Update ()
{
timer -= Time.deltaTime;
timerseconds.text = timer.ToString("f0");
if (timer <= 0)
{
Invoke("LoadScene", 2.5f);
}
}
void LoadScene()
{
SceneManager.LoadScene("OLYMPUS");
}
}
For more begginers, you may change Private to Public and add this on top,
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;