Am I doing something wrong?

Rick’s method to add the delay for loading the scene works without any issues, but I was wondering why my method isn’t working

My SceneLoader:

public IEnumerator LoadEndMenu()
    {
        Debug.Log("A");

        yield return new WaitForSeconds(delayToEndMenu);

        Debug.Log("B");

        SceneManager.LoadScene(2);
    }

my Player:

private void Die()
    {
        StartCoroutine(sceneLoader.LoadEndMenu());

        Destroy(gameObject);

        AudioSource.PlayClipAtPoint(playerDeathSFX, Camera.main.transform.position, playerDeathSFXVolume);
    }

everything that’s before: yield return new WaitForSeconds(delayToEndMenu);
works, but the things after it don’t, what am I doing wrong?

Hi Haisp,

What does “my method isn’t working” mean? What did you expect to happen, what happened instead?


See also:

There should be a delay before loading the new scene after the player dies, what ended up happening is A gets written in the console when the player dies and everything after yield doesn’t work, so there’s some sort of issue that’s doing something in the corotuine

Hard to say with the amount of code shown, what is the value of delayToEndMenu.

It’s set to 2f, this is the entire code:

public class SceneLoader : MonoBehaviour
{
    [SerializeField] float delayToEndMenu = 2f;

    public void LoadStartMenu()
    {
        SceneManager.LoadScene(0);
    }

    public void LoadGame()
    {
        SceneManager.LoadScene(1);
    }

public IEnumerator LoadEndMenu()
    {
        Debug.Log("A");

        yield return new WaitForSeconds(delayToEndMenu);

        Debug.Log("B");

        SceneManager.LoadScene(2);
    }

    public void QuitGame()
    {
        Application.Quit();
    }
}

Your delayToEndMenu variable is exposed in your Inspector. Check its value there as the Inspector overrides the value in your code. Increase it for testing purposes, maybe to 5 or 10 in the Inspector.

may also be that the game object the script is attached to is being destroyed befor the script finishes running.

It was set to 2, I changed it to 5 and nothing happened still

The object that it’s attached to isn’t getting destroyed.

Can try doing something more simple.

Example:

float delay = 5f;
bool playerDead = false;

// Update is called once per frame 
void Update()
{ 
    if (playerDead == true)
    {
        delay -= Time.deltaTime;
 
        if (delay <= 0) 
        {
            // Load level code here.
        } 
    }
}

Sorry if its messy, on my phone.

How are you getting on with this, @Haisp?

I ended up following Rick’s method, but I still don’t know why my method isn’t working.

Your SceneLoader looks fine. Maybe the problem is/was that LoadEndMenu was not called via StartCoroutine but directly. Or something else called one of your other public methods.

Change the “StartCoroutine(sceneLoader.LoadEndMenu());” to

This topic was automatically closed after 14 days. New replies are no longer allowed.

Privacy & Terms