Yield return StartCoroutine Not Finishing Before Moving On
Exactly as the title says. I have no idea why it isn't working. I'm using Piglet to load a few GLTF Files at runtime (Awesome asset by @awesomesaucelabs) and I need to wait until the models have finished loading before moving on. For some reason, that Coroutine just isn't going all the way through before moving on: Here's my code.
// IN SCRIPT 'A'
IEnumerator loadObjectsIntoScene()
{
// THIS COROUTINE WORKS FINE
yield return StartCoroutine(database.initializeCustomTextureLibrary());
// THIS ONE ISN'T FINISHING
yield return StartCoroutine(database.LoadAllCustomModels());
// DO OTHER STUFF
}
Then, In the other script is the original function. Hopefully, the code makes sense even if you're not familiar with Piglet:
public IEnumerator LoadAllCustomModels()
{
Debug.Log("MODELS LOADING");
Array.Clear(filesInFolder, 0, filesInFolder.Length);
filesInFolder = Directory.EnumerateFiles(modelPath, "*.*", SearchOption.AllDirectories)
.Where(s => s.EndsWith(".glb") || s.EndsWith(".gltf") || s.EndsWith(".zip")).ToArray();
for (int i = 0; i < filesInFolder.Length; i++)
{
GltfImportTask newTask = RuntimeGltfImporter.GetImportTask(filesInFolder[i]);
newTask.OnCompleted = OnModelLoaded;
newTask.OnProgress = OnProgress;
importTasks.Add(newTask);
}
yield return null;
while (!isFinishedLoadingCustomModels)
{
for (int i = 0; i < importTasks.Count; i++)
{
importTasks[i].MoveNext(); // THIS IS REQUIRED EVERY FRAME IN ORDER TO IMPORT THE MODE
}
if (filesInFolder.Length == customModelLibrary.Count) // ONCE ALL MODELS IN THE FOLDER ARE FINISHED LOADING
{
isFinishedLoadingCustomModels = true;
Debug.Log("MODELS DONE LOADING");
yield break;
}
}
}
In the console I'm getting the first ("MODELS LOADING") message, but not the second ("MODELS FINISHED LOADING") message. Though still, the code in the first scripts moves on before all models are loaded. Any and all help would be greatly appreciated. Happy holidays!
EDIT: If I move this to update instead of in the coroutine, Unity just hangs...
if (!isFinishedLoadingCustomModels)
{
for (int i = 0; i < importTasks.Count; i++)
{
importTasks[i].MoveNext();
}
}