Problem with loading Game Over scene. Please help!

Hi. I have a problem with loading Game Over scene. What I’m trying to do is when player dies, the game over scene appears with 1 second delay.

So what is the problem you’re having? By the way, it’s preferable that you paste your code into the forums using code tags instead of uploading a screenshot of the code.

I’m trying to make that when a player dies, the game loads game over scene but with a delay.
This part of code loads the game over scene but i can’t put in it “yield return new WaitForSeconds(2);”

void Update()
{
if (Player == null)
{
SceneManager.LoadScene(“GameOver”);
}
}

…I know I should use IEnumerator in order to use “yield…” but I need something that is constantly checking if player is alive (that’s why I used upadte function) and I don’t know how.

Please use code tags when you’re adding code to a post.

You don’t have to check if the player is dead every frame, you just have to check when he takes damage, right?

Does your Player have a component that handles his health? You could add an event to that for “OnDamaged” or even more specifically “OnDead”. Then you can have this GameController listen for that event, and then start the coroutine to show the game over scene.

Here’s an example of what I mean:

using UnityEngine;
using UnityEngine.Events;
public class Player : MonoBehaviour {

    private float health;

    public UnityEvent OnDead;

    public void TakeDamage(float damage) {
        health -= damage; // subtract from health
        health = Mathf.Max(0f, health); // choose the greater value to keep health >= 0
        // if theres no health left
        if(health == 0f) {
            OnDead.Invoke(); // fire the event
        }
    }
}
using UnityEngine;
using UnityEngine.SceneManagement;
using System.Collections;
public class GameController : MonoBehaviour {
    public Player player; // reference to the Player component
    public float gameOverDelay = 2f;
    public string gameOverSceneName = "GameOver";

    private void Start() {
        player.OnDead.AddListener(OnPlayerDead); // when this event is fired, call OnPlayerDead
    }

    private void OnPlayerDead() {
        player.OnDead.RemoveListener(OnPlayerDead); // stop listening for the dead event
        StartCoroutine(GameOver());
    }

    private IEnumerator GameOver() {
        yield return new WaitForSeconds(gameOverDelay);
        SceneManager.LoadScene(gameOverSceneName);
    }
}

Hi :slight_smile: so i finally got some time to test your code out. Didn’t do it exactly like you wrote but you gave me an idea and it works. Thank you so much for your time and help, much appreciated.

1 Like