unity infinitely loads level in awake or crashes

I have looked at loads and tried lots of different things but i’m not sure whats wrong. What i’m trying to do is load a specific scene in an awake but no matter what i try unity just crashes or infinitely loads the level. I’ve looked t lots of threads similar to this problem but cant find a solution, any help would be greatly appreciated!

Code below:

    IEnumerator Loadthatscene()
    {
        yield return 0; // this stops unity from crashing when i load the level
        AsyncOperation asyncLoad = SceneManager.LoadSceneAsync(0);
        while (!asyncLoad.isDone)
        {
            yield return null;
        }


    }
    void Awake()
    {
        StartCoroutine(Loadthatscene());
    
    }

I’m not sure if i’m even doing this right but this seems to be the best way to do this from what i’ve seen.

Originally i wanted to have the option to do a checkbox so when creating new levels i could play it as it would be as an actual game or test a level but now i’m just trying to get this to work.

That code is fine, so if Unity’s in an infinite loop, it’s somewhere else.

Do you have any levels in your build settings? If you don’t you should be getting errors instead of hanging, but it’s worth looking into.

1 Like

Thanks i’m not sure whats wrong then as i put the level into my build settings. I did read somewhere that it might have something to do with it not loading the level properly then repeatedly retrying but that should’ve fixed it

and would it make a difference if that was put in an awake?

UUUh, okay, so if this script is in an object that’s in level 0, that would cause an infinite loop.

What happens then is that as you load level 0, the script in that level would get an Awake call, which would cause it to load level 0. And so on forever.

I thought that too so i put in a if variable is true do this then afterwards make it false but that didn’t make a difference as it kept doing it, i even checked with debugs to see if it was actually making variable false and it was.

That’s because the variable’s on the object in the old level. The copy in the new level has it’s own variables (that makes sense - right? You don’t want enemies in a loaded level to have the health of the enemies in the old level).

The common way to do this is to have a load scene that contains your script, and then have a different scene that you’re loading into. You shouldn’t be loading the load scene when the load scene starts.

ah thanks i’ll try figure out how to do that