Reputation: 103
I am very new to Unity and C#, and am just starting to learn the basics. I made a simple game that has a cube moving forward, and if it hits an obstacle, the game restarts. However, when I try to use Invoke to delay the time after the game restarts when the cube collides, the restart is instant.
I haven't been able to try much since I am still new to C# and Unity.
This is my GameManager script:
using UnityEngine;
using UnityEngine.SceneManagement;
public class GameManager : MonoBehaviour
{
bool gameHasEnded = false;
public float restartDelay = 3f;
public void EndGame()
{
if (gameHasEnded == false)
{
gameHasEnded = true;
Debug.Log("Game Over!");
Invoke("Restart", restartDelay);
Restart();
}
}
void Restart()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
}
When the player collides with an object (Obstacle script):
using UnityEngine;
public class PlayerCollision : MonoBehaviour
{
public PlayerMovement movement;
void OnCollisionEnter(Collision collisionInfo)
{
if (collisionInfo.collider.tag == "Obstacle")
{
movement.enabled = false;
FindObjectOfType<GameManager>().EndGame();
}
}
}
I want the restart to be delayed so the game doesn't restart instantly. Any help would be greatly appreciated :)
Upvotes: 0
Views: 2461
Reputation: 4056
You called Restart()
after invoking the Restart
function with a delay.
// ...
if (gameHasEnded == false) {
gameHasEnded = true;
Debug.Log("Game Over!");
Invoke("Restart", restartDelay);
// This below is called instantly.
// It does not wait for the restartDelay.
Restart();
}
// ...
Just simply remove the Restart()
call like so:
if (gameHasEnded == false) {
gameHasEnded = true;
Debug.Log("Game Over!");
Invoke("Restart", restartDelay);
}
Note that the code does not 'pause' at Invoke()
. Think of Invoke
as a async/coroutine operation.
Upvotes: 1