- Home /
Restart Delay
I have the code below, but it doesn't have a delay even though there should be.
using UnityEngine.SceneManagement; using UnityEngine; using System.Collections;
public class GameManagerCubic : MonoBehaviour
{
bool gameHasEnded = false;
public float restartDelay = 2f;
public void EndGame()
{
if (gameHasEnded == false)
{
gameHasEnded = true;
Debug.Log("OVER OVER");
Invoke("Restart", restartDelay);
}
}
void Restart ()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
}
Are you SURE the value of restartDelay
is greater than 0 IN THE INSPECTOR?
public void EndGame()
{
if (gameHasEnded == false)
{
gameHasEnded = true;
Debug.Log("Invoking Restart in " + restartDelay + " second(s)");
Invoke("Restart", restartDelay);
}
}
I tried using the code you submitted, but It isn't working.
$$anonymous$$y code wasn't supposed to fix anything. It prints the value of the restartDelay
variable. What is its value?
Are you sure you don't destroy the gameObject / disable the script before the EndGame
is called?
Sounds like you're destroying the game object the script is attached to after calling "EndGame". $$anonymous$$ake sure this isn't the case:
In Play mode, select the game object with the script attached. Then when "EndGame" gets triggered, make sure it remains in the scene hierarchy.
Answer by FriezKing · Dec 31, 2018 at 07:46 PM
Instead of using the Invoke function, have you thought of using a coroutine?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class GameManagerCubic : MonoBehaviour
{
bool gameHasEnded = false;
public float restartDelay = 2f;
public void EndGame()
{
if (gameHasEnded == false)
{
gameHasEnded = true;
Debug.Log("OVER OVER");
Restart();
}
}
void Restart ()
{
StartCoroutine("Restart2");
}
IEnumerator Restart2()
{
yield return new WaitForSeconds(restartDelay);
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
}
I'm no expert, but I'm pretty sure that should fix it! Please tell me if you recieve any errors.
That didn't work, I don't understand, I'm doing everything right in the inspector and I used the code, but it isn't working.
Your answer
Follow this Question
Related Questions
,Restart Scene after level Completion 0 Answers
Restart Game from Button, not SceneMangement 1 Answer
Current Level Load Again After Level Completion 2 Answers
i have a button to restart the same scene but it dont works (with images) 7 Answers
I bought unity games for reskin. package name how do I change the game name?,reskin 0 Answers