docs.unity3d.com
Search Results for

    Show / Hide Table of Contents

    Runtime Export

    You can export individual GameObjects or entire scenes to glTF™ files at runtime.

    Include Required Shaders

    To be able to export certain textures correctly, a couple of shaders are required. They are located at Runtime/Shader/Export. Make sure to include them all in your build.

    The easiest way to include them is to add glTFExport.shadervariants to the list of Preloaded Shaders under Project Settings > Graphics > Shader Loading.

    Export via Script

    NOTE: The GLTFast.Export namespace can only be used if you reference both glTFast and glTFast.Export Assemblies in your Assembly Definition.

    Here's a step-by-step guide to export a GameObject hierarchy/scene from script

    • Create an instance of GameObjectExport
    • Add content via AddScene
    • Two options for the final export
      • Call SaveToFileAndDispose to export a glTF to a file(s)
      • Call SaveToStreamAndDispose to export to a Stream

    glTF export might create more than one file. For example the binary buffer is usually a separate .bin file and textures might be separate files as well.

    using UnityEngine;
    using GLTFast.Export;
    
    class SimpleExport : MonoBehaviour
    {
    
        [SerializeField]
        string destinationFilePath;
    
        async void Start()
        {
    
            // Example of gathering GameObjects to be exported (recursively)
            var rootLevelNodes = GameObject.FindGameObjectsWithTag("ExportMe");
    
            // GameObjectExport lets you create glTF files from GameObject hierarchies
            var export = new GameObjectExport();
    
            // Add a scene
            export.AddScene(rootLevelNodes);
    
            // Async glTF export
            var success = await export.SaveToFileAndDispose(destinationFilePath);
    
            if (!success)
            {
                Debug.LogError("Something went wrong exporting a glTF");
            }
        }
    }
    

    After calling SaveToFileAndDispose the GameObjectExport instance becomes invalid. Do not re-use it.

    Further, the export can be customized by passing ExportSettings, GameObjectExportSettings and injectables to GameObjectExport's constructor:

    
    // CollectingLogger lets you programmatically go through
    // errors and warnings the export raised
    var logger = new CollectingLogger();
    
    // ExportSettings and GameObjectExportSettings allow you to configure the export
    // Check their respective source for details
    
    // ExportSettings provides generic export settings
    var exportSettings = new ExportSettings
    {
        Format = GltfFormat.Binary,
        FileConflictResolution = FileConflictResolution.Overwrite,
    
        // Export everything except cameras or animation
        ComponentMask = ~(ComponentType.Camera | ComponentType.Animation),
    
        // Boost light intensities
        LightIntensityFactor = 100f,
    
        // Ensure mesh vertex attributes colors and texture coordinate (channels 1 through 8) are always
        // exported, even if they are not used/referenced.
        PreservedVertexAttributes = VertexAttributeUsage.AllTexCoords | VertexAttributeUsage.Color,
    };
    
    // GameObjectExportSettings provides settings specific to a GameObject/Component based hierarchy
    var gameObjectExportSettings = new GameObjectExportSettings
    {
        // Include inactive GameObjects in export
        OnlyActiveInHierarchy = false,
    
        // Also export disabled components
        DisabledComponents = true,
    
        // Only export GameObjects on certain layers
        LayerMask = LayerMask.GetMask("Default", "MyCustomLayer"),
    };
    
    // GameObjectExport lets you create glTFs from GameObject hierarchies
    var export = new GameObjectExport(exportSettings, gameObjectExportSettings, logger: logger);
    
    // Example of gathering GameObjects to be exported (recursively)
    var rootLevelNodes = GameObject.FindGameObjectsWithTag("ExportMe");
    
    // Add a scene
    export.AddScene(rootLevelNodes, "My new glTF scene");
    
    // Async glTF export
    var success = await export.SaveToFileAndDispose(destinationFilePath);
    
    if (!success)
    {
        Debug.LogError("Something went wrong exporting a glTF");
    
        // Log all exporter messages
        logger.LogAll();
    }
    
    

    NOTE: Exporting to a Stream currently only works for self-contained glTF-Binary files (where the binary buffer and all textures are included in the .glb file). Trying other export settings will fail.

    Scene Origin

    When adding GameObjects to a glTF scene, the resulting glTF root nodes' positions will be their original GameObjects' world position in the Unity scene. That might be undesirable (e.g. if the scene is far off the origin and thus not centered), so AddScene allows you to provide an inverse scene origin matrix that'll be applied to all root-level nodes.

    Here's an example how to export a GameObject, discarding its transform:

    var export = new GameObjectExport();
    
    // Add a scene
    export.AddScene(
        // Only the current gameObject as root node.
        new[] { gameObject },
        // The worldToLocalMatrix counter-acts any world-space transform, effectively moving the resulting
        // root node to the origin.
        gameObject.transform.worldToLocalMatrix,
        "Node at origin glTF scene"
        );
    

    Vertex Attribute Discarding

    In certain cases glTFast discards mesh vertex attributes that are not used or required. This not only reduces the resulting glTF's file size, but in case of vertex colors, is necessary to preserve visual consistency.

    This behavior might be undesirable, for example in authoring workflows where the resulting glTF will be further edited. In that case vertex attribute discarding can be disabled on a per-attribute basis by setting ExportSettings' PreservedVertexAttributes mask.

    Examples of vertex attribute discarding:

    • Vertex colors, when the assigned material(s) do not use them.
    • Normals and tangents, when the assigned material is unlit and does not require them for shading.
    • When no material was assigned, a default fallback material will be assumed. This does not require tangents nor texture coordinates, hence those are discarded.

    NOTE: Not all cases of potential discarding are covered at the moment (e.g. unused texture coordinates when no textures are assigned).

    Draco Compression

    Unity glTFast supports applying Google Draco™ 3D Data compression to meshes. This requires the Draco for Unity package to be installed.

    // ExportSettings provides generic export settings
    var exportSettings = new ExportSettings
    {
        // Enable Draco compression
        Compression = Compression.Draco,
        // Optional: Tweak the Draco compression settings
        DracoSettings = new DracoExportSettings
        {
            positionQuantization = 12
        }
    };
    

    Trademarks

    Unity® is a registered trademark of Unity Technologies.

    Khronos® is a registered trademark and glTF™ is a trademark of The Khronos Group Inc.

    Draco™ is a trademark of Google LLC.

    In This Article
    Back to top
    Copyright © 2024 Unity Technologies — Trademarks and terms of use
    • Legal
    • Privacy Policy
    • Cookie Policy
    • Do Not Sell or Share My Personal Information
    • Your Privacy Choices (Cookie Settings)