PotatoProgrammer
PotatoProgrammer

Reputation: 3

I'm using a coroutine and the code is stopping at yield return without resuming after the given time

This is a script I'm attaching to a button in order to load the next level when clicked

using System.Collections.Generic;
using UnityEngine;
using System;
using UnityEngine.SceneManagement;
public class LoadNextLevel : MonoBehaviour
{
    static Action<string> LoadNextLvl;
    void Start()
    {
        //The issue isn't with the delegate because i tried running the 
        //code without it
        LoadNextLvl += (string name) => StartCoroutine("LoadFunc" , name);
    }
    IEnumerator LoadFunc(string name)
    {
        //This is to load the next level, it has nothing to do with the bug
        int levelnum = int.Parse(name[5].ToString());
        levelnum++;
        SceneManager.LoadScene("Loading");
        //i want to wait for a certain amount of time then load the next scene
        yield return new WaitForSeconds(2f);
        //For some reason the code stops here and doesn't continue even after
        //I wait, in fact I tried yield return null but the same issue still
        //occurs.
        SceneManager.LoadScene("Level" + levelnum);

    }
    public void Load()
    {
        //This function will be called using a button
        LoadNextLvl(gameObject.scene.name);
    }
}

As I explained in the comments, I tried different things until i narrowed down the issue to the fact that it stops at yield return even though I did exactly like all the tutorials I found.

Upvotes: 0

Views: 111

Answers (1)

derHugo
derHugo

Reputation: 90679

When you do

SceneManager.LoadScene("Loading");

the current scene is unloaded and this component most probably along with it so your Coroutine is only executed to the first yield and then never continues.

Also you really don't need that delegate. Why not simply call your method directly like this:

public class LoadNextLevel : MonoBehaviour
{
    private IEnumerator LoadFunc()
    {
        var levelnum = int.Parse(gameObject.scene.name[5].ToString());
        levelnum++;
        // Make sure this is not destroyed when the scene is unloaded
        DontDestroyOnLoad (gameObject);
        SceneManager.LoadScene("Loading");
        
        yield return new WaitForSeconds(2f);

        SceneManager.LoadScene("Level" + levelnum);

        // Then once you don't need this anymore now destroy it
        Destroy (gameObject);
    }

    public void Load()
    {
        StartCoroutine(LoadFunc());
    }
}

Instead of going by strings you could also use

var nextIndex = SceneManager.GetActiveScene().buildIndex + 1;

and then later

SceneManager.LoadScene(nextIndex);

Upvotes: 1

Related Questions