- Home /
How to add delay before showing GUI Button?
I'm trying to make a restart button but I always get this error that OnGUI can't be a coroutine. so how do i add a delay without using yield?
Here's my code:
function OnGUI(){
if(gameOver == true)
{
yield WaitForSeconds (gameOverDelay);
Time.timeScale = 0.0;
if (GUI.Button (Rect(20,20,100,20), "Restart")) {
Application.LoadLevel(Application.loadedLevel);
gameOver = false;
Time.timeScale = 1.0;
}
}
}
Could you please show me the code appropriate for this? and could you explain the error for me (sorry i'm kinda new at this). Thank you :D
Answer by ScroodgeM · Aug 04, 2012 at 07:37 PM
var ShowButtonTime : float;
function ShowButtonWithDelay() { ShowButtonTime = Time.time + gameOverDelay; }
function OnGUI(){
if(gameOver == true && Time.time >= ShowButtonTime)
{
Time.timeScale = 0.0;
if (GUI.Button (Rect(20,20,100,20), "Restart")) {
Application.LoadLevel(Application.loadedLevel);
gameOver = false;
Time.timeScale = 1.0;
}
}
}
soo... when did you use the function ShowButtonWithDelay()?
Answer by aldonaletto · Aug 04, 2012 at 07:40 PM
Start a timer when gameOver becomes true, and when this timer ends enable the button with the variable restartEnabled:
private var restartEnabled = false; private var tEnd: float = 0;
function Update(){ // if gameOver became true... if (gameOver){ if (tEnd == 0){ // set the timer tEnd = gameOverDelay; } else { // and decrement it in the next Updates tEnd -= Time.deltaTime; if (tEnd <= 0){ // if timer ended enable button restartEnabled = true; } } } }
function OnGUI(){ if (restartEnabled){ if (GUI.Button (Rect(20,20,100,20), "Restart")) { Application.LoadLevel(Application.loadedLevel); } } }
Answer by drawcode · Aug 04, 2012 at 08:44 PM
You can still use a coroutine and just put all your game over code behind it from StartCoroutine().
function OnGUI(){
if(gameOver == true)
{
StartCoroutine(gameOverCoroutine());
}
}
IEnumerator gameOverCoroutine() {
yield WaitForSeconds (gameOverDelay);
Time.timeScale = 0.0;
if (GUI.Button (Rect(20,20,100,20), "Restart")) {
Application.LoadLevel(Application.loadedLevel);
gameOver = false;
Time.timeScale = 1.0;
}
}
OR
you can also just call Invoke("methodName", delay); to call something after a certain amount of time.
var gameOver = false;
var gameOverDelay = 5f;
function OnGUI(){
if(gameOver == true)
{
Invoke("gameOverDelayed", gameOverDelay);
}
}
function gameOverDelayed() {
Time.timeScale = 0.0;
if (GUI.Button (Rect(20,20,100,20), "Restart")) {
Application.LoadLevel(Application.loadedLevel);
gameOver = false;
Time.timeScale = 1.0;
}
}
I tried both, and i keep on getting errors.
Invoke: GUI Buttons are for OnGUI only
Coroutine: It keeps on saying that I need to put ; or } at the end.
True sorry I never use OnGUI anymore as I use a UI toolkit and forgot about that restriction. Aldo's response will work with OnGUI elements perfectly.