How to unload a level after leaving a trigger area?
I have a game that will have several massive levels that flow right into each other (it's a Metroidvania game), and so I need to unload levels when the character leaves those areas, so that it doesn't crash the game due to using too much memory.
I've already tried:
void OnTriggerExit2D(Collider2D coll)
{
SceneManager.UnloadScene(sceneIndex);
}
However, I read somewhere that you can't call UnloadScene
from physics triggers for some reason. https://docs.unity3d.com/ScriptReference/SceneManagement.SceneManager.UnloadScene.html
But they say to use UnloadSceneAsync
, which doesn't exist. The link in the documentation is broken and my program won't compile when I try to use it.
How to go about this? How does one unload a scene after the character leaves it?
Answer by JincSoft · Nov 02, 2016 at 07:33 AM
Something like this (untested):
void Update()
{
if(flag)
{
//prevents multiple calls to UnloadScene
flag = false;
SceneManager.UnloadScene(sceneIndex);
}
}
void OnTriggerExit2D(Collider2D coll)
{
flag = true;
}
Not the prettiest but it should work.
I was hoping for a better answer, but this workaround should work if there is no other better answer. Thanks for suggesting this! I can't believe I didn't already think of this!
I looked for the UnloadAsync command but it seems to have disappeared off the face of the planet. Another thing to try is
void OnTriggerExit2D(Collider2D coll)
{
Unload$$anonymous$$yScene();
}
void Unload$$anonymous$$yScene()
{
//if sceneIndex is public this may work, if not just pass it into the function
Scene$$anonymous$$anager.UnloadScene(sceneIndex);
}
This way you technically aren't calling it from a callback.
Edit: code formatting is a pain to get right
I have a static class that manages scene transitions, and calling those methods did not prevent this problem. It really seems like flags or coroutines are your only options.