Batch Export Scene Roots to glTF Files
A common Editor scripting use case is exporting GameObjects to individual .glb files.
The example below adds a Tools > glTFast Examples > Batch Export menu entry.
[MenuItem("Tools/glTFast Examples/Batch Export")]
static async Task BatchExportAllObjects()
{
var currentScene = SceneManager.GetActiveScene();
var rootObjects = currentScene.GetRootGameObjects();
var exportSettings = new ExportSettings
{
Format = GltfFormat.Binary
};
var logger = new ConsoleLogger();
try
{
for (var index = 0; index < rootObjects.Length; index++)
{
var rootObject = rootObjects[index];
EditorUtility.DisplayProgressBar(
"glTF Batch Export", rootObject.name, index / (float)rootObjects.Length);
var export = new GameObjectExport(exportSettings, logger: logger);
export.AddScene(new[] { rootObject }, rootObject.name);
var success = await export.SaveToFileAndDispose(
$"Assets/{rootObject.name}.glb",
// Edit Mode does not pump the main-thread SynchronizationContext;
// awaited I/O continuations could hang. Force the synchronous path.
forceSync: true
);
if (!success)
{
Debug.LogError($"Exporting {rootObject.name} failed.");
}
}
}
finally
{
EditorUtility.ClearProgressBar();
AssetDatabase.Refresh();
}
}
A few details worth highlighting:
forceSync: trueis required because the menu item runs in Edit Mode — see Editor Scripting: Enforce Synchronous I/O for the rationale.
Trademarks
Unity® is a registered trademark of Unity Technologies.
Khronos® is a registered trademark and glTF™ is a trademark of The Khronos Group Inc.