简体   繁体   中英

Invoke Can't Be Called

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:)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM