Hi everyone! I’m developing a room system for a Metroidvania game. Each room was made in a separate scene, and when the player enters the room bounds, it loads all scenes nearby that room and unloads all scenes far away.
Loads the scenes:
IEnumerator LoadNearbyScenesAsync()
{
List<AsyncOperation> sceneLoads = new List<AsyncOperation>();
for (int i = 0; i < nearbyRoomsName.Count; ++i)
{
if (!SceneHandler.sceneHandlerInstance.GetCurrentScenesLoaded().Contains(nearbyRoomsName[i]))
{
AsyncOperation sceneLoading = SceneManager.LoadSceneAsync(nearbyRoomsName[i], LoadSceneMode.Additive);
sceneLoading.allowSceneActivation = false;
sceneLoads.Add(sceneLoading);
while (sceneLoads[i].progress < 0.9f)
{
yield return null;
}
}
}
for (int i = 0; i < sceneLoads.Count; ++i)
{
sceneLoads[i].allowSceneActivation = true;
while (!sceneLoads[i].isDone)
{
yield return null;
}
if (!SceneHandler.sceneHandlerInstance.GetCurrentScenesLoaded().Contains(this.gameObject.scene.name))
{
SceneHandler.sceneHandlerInstance.SetSceneAsLoaded(nearbyRoomsName[i]);
}
}
UnloadFarLevels();
}
Unloads the scenes:
IEnumerator UnloadFarScenes()
{
List<AsyncOperation> sceneUnloads = new List<AsyncOperation>();
for (int i = 0; i < SceneHandler.sceneHandlerInstance.GetCurrentScenesLoaded().Count; ++i)
{
if (!nearbyRoomsName.Contains(SceneHandler.sceneHandlerInstance.GetCurrentScenesLoaded()[i]))
{
AsyncOperation sceneUnloading = SceneManager.UnloadSceneAsync(SceneHandler.sceneHandlerInstance.GetCurrentScenesLoaded()[i]);
sceneUnloads.Add(sceneUnloading);
SceneHandler.sceneHandlerInstance.SetSceneAsUnloaded(SceneHandler.sceneHandlerInstance.GetCurrentScenesLoaded()[i]);
while (!sceneUnloads[i].isDone)
{
yield return null;
}
}
}
}
It is working kinda well, but sometimes I get an Out of Range Exception, and some scenes start loading, but never loads. Should be some silly logic mistake, any ideias on what should it be?