Kyle Rebozzi
Kyle Rebozzi

Reputation: 21

How do I unload additive scenes?

I'm making a tank battle game that randomly generates new levels after every round. In my game manager I'm trying to have the round started with an additive loaded scene from a random range index and then end by unload the scene and then loading in a new random scene. However, every attempt I make results in some form of error.

I've been constantly directed to LoadLevelAsync but it seems to just give me more questions that no one seems to answer.

Here's how it's currently laid out:

//Load random level scene
        int index = Random.Range(2, 4);
        SceneManager.LoadSceneAsync(index, LoadSceneMode.Additive);
        Debug.Log("SceneLoaded");


//Unload current scene and load new random level scene

        int index = Random.Range(2, 4);
        SceneManager.UnloadSceneAsync(index);
        SceneManager.LoadSceneAsync(index, LoadSceneMode.Additive);
        Debug.Log("SceneLoaded");

With the way this code is set, it seems to work fine if the new random level is a repeat of the previously used level, but if the called level is different then it gives me an error and crashes.

Any advice on where to go from here is much appreciated. I'm not a programmer in any way so simple yet detailed explanations are necessary. Thank you.

Upvotes: 2

Views: 5351

Answers (2)

DmitriyK
DmitriyK

Reputation: 63

I found working solution. Maybe it will be still relevant.

// Get count of loaded Scenes and last index
var lastSceneIndex = SceneManager.sceneCount - 1

// Get last Scene by index in all loaded Scenes
var lastLoadedScene = SceneManager.GetSceneAt(lastSceneIndex)

// Unload Scene
SceneManager.UnloadSceneAsync(lastLoadedScene);

SceneManager.GetSceneAt() - Get the Scene at index in the SceneManager's list of loaded Scenes

SceneManager.sceneCount - The total number of currently loaded Scenes


Upvotes: 2

sourav satpati
sourav satpati

Reputation: 39

//Load random level scene
        int index = Random.Range(2, 4);
        SceneManager.LoadSceneAsync(index, LoadSceneMode.Additive);

Suppose if here 'index' number is 3 and scene 3 is loaded.ok no problem.

//Unload current scene and load new random level scene

        int index = Random.Range(2, 4);
        SceneManager.UnloadSceneAsync(index);

And here 'index' number is generate again such as 2.You want to unlode scene 2 but is not there thats the problem.

Solution :-

//Load random level scene
        int index = Random.Range(2, 4);
        int lodedScene = index;
        SceneManager.LoadSceneAsync(index, LoadSceneMode.Additive);
        Debug.Log("SceneLoaded");


//Unload current scene and load new random level scene

        int index = Random.Range(2, 4);
        SceneManager.UnloadSceneAsync(lodedScene);
        SceneManager.LoadSceneAsync(index, LoadSceneMode.Additive);
        Debug.Log("SceneLoaded");

Upvotes: 0

Related Questions