UnityGLTF Documentation

repository·main·Indexed 24 days ago

https://github.com/khronosgroup/unitygltf

A pure C# library for Unity (version 2.19.5) providing robust import and export capabilities for the glTF 2.0 specification. It supports animations, materials, and extensions, including KHR_interactivity for Visual Scripting Graphs and KHR_animation_pointer for arbitrary property animations. Designed for Unity LTS versions (2021.3+, 2022.3+, 6000.0+) using Linear colorspace and URP or Built-In Render Pipelines. Includes the UnityGLTF/PBRGraph shader for extended glTF shading models.

Tokens
5.5K
Snippets
6
Records
23
Agent score
31%

What's inside UnityGLTF

  1. Extend UnityGLTF with custom Import/Export plugins

    main

    UnityGLTF provides a plugin system to modify node structures, extension data, or materials during the import/export process. Plugins are ScriptableObjects enabled via Project Settings > UnityGLTF.

    To create a plugin:

    1. Create a class inheriting from GLTFImportPlugin or GLTFExportPlugin (this holds the settings).
    2. Create a class inheriting from GLTFImportPluginContext or GLTFExportPluginContext (this contains the actual callbacks).
    3. Implement CreateInstance in the plugin class to return the context instance.
    4. Override the desired callbacks in the context class.

    If your plugin handles custom extension data, implement GLTF.Schema.IExtension for serialization.

    // Example for custom export plugin
    public class MyExportPlugin : GLTFExportPlugin
    {
        public override string DisplayName { get => "My Custom Plugin"; }
        public override bool EnabledByDefault => true;
        public override bool AlwaysEnabled => false;
        
        public override GLTFExportPluginContext CreateInstance(ExportContext context)
        {
            return new MyExportPluginContext();
        }
    }
    
    public class MyExportPluginContext: GLTFExportPluginContext
    {
        public override bool ShouldNodeExport(GLTFSceneExporter exporter, GLTFRoot gltfRoot, Transform transform)
        {
            return !transform.CompareTag("ignore");
        }
    }
    
    // Example for custom import plugin
    public class MyImportPlugin: GLTFImportPlugin
    {
        public override string DisplayName => "My Import Plugin";
        public override string Description => "";
        
        public override GLTFImportPluginContext CreateInstance(GLTFImportContext context)
        {
            return new MyImportPluginContext();
        }
    }
    
    public class MyImportPluginContext: GLTFImportPluginContext
    {
        public override void OnAfterImportScene(GLTFScene scene, int sceneIndex, GameObject sceneObject)
        {
            // Set all to static
            var objs = sceneObject.GetComponentsInChildren<Transform>();
            foreach (var obj in objs)
                obj.gameObject.isStatic = true;
        }
    }
  2. How KHR_interactivity Visual Scripting export works

    main

    The Visual Scripting Graph Exporter converts Unity Visual Scripting logic into KHR_interactivity graphs. To maintain compatibility with the glTF extension, certain Unity features are "flattened" during export:

    • SubGraphs: These are flattened into the main graph.
    • Variables: Scoped variables are exported as variables with unique names to prevent conflicts. Note that "Saved" variables are not supported.
    • Multiple Graphs: Multiple Visual Scripting Graphs in a single glTF file are merged into one single KHR_interactivity graph.
    • Lists/Arrays: Capacity cannot be changed at runtime; ensure lists are created with sufficient size in the graph.

    Supported Logic & Operations

    • Math, Vector, and Matrix operations.
    • Logic operations.
    • Material editing (Get/Set of floats, colors, texture offset/scale).
    • Property interpolation (using the "Interpolate ..." family of nodes).
    • Custom Events and Coroutines.
    • Partial Animator support (starting an animation is supported, but automatic graph transitions are not).

    Limitations

    • String manipulation is not supported by the KHR_interactivity extension.
    • Some nodes have specific limitations. You can check compatibility in the Visual Scripting Editor (supported nodes are highlighted) or by clicking Project Settings > UnityGLTF > Export > KHR_interactivity (VisualScripting) > Log supported Visual Scripting Units to see the full list in the console.
  3. Ensure shader variants are included in standalone builds

    main

    When modifying materials at runtime (e.g., using Material.EnableKeyword to toggle features like normal maps, emission, or alpha modes), Unity's standalone player may not include the required shader variants unless they are explicitly referenced. Because GLTFSceneImporter.cs enables these keywords dynamically based on glTF data, you must ensure the variants are compiled into your build using one of the following two methods:

    Method 1: Use a ShaderVariantCollection

    Create a ShaderVariantCollection asset and add the specific keywords/variants required by your glTF assets to the collection.

    Method 2: Use the Resources folder

    Add a material to the Assets/Resources folder that uses the required shader configuration. To ensure Unity includes the variant, the material must actually use the features:

    • Assign textures to the texture fields.
    • Change Colors to something other than black.
    • Change float values to something other than 0.

    Note: The material does not need to be assigned to an object in a scene; its presence in the Resources folder is sufficient for Unity to include its shader variants in the build.

  4. Use UnityGLTF/PBRGraph for glTF materials

    main

    To use the extended glTF shading model in Unity (including support for transmission, rough refraction, sheen, clearcoat, and per-texture UV control), use the UnityGLTF/PBRGraph shader. This is the recommended shader for achieving perfect roundtrips between Unity and glTF.

    For unlit materials, use UnityGLTF/UnlitGraph.

  5. Compare UnityGLTF and glTFast

    main

    UnityGLTF and glTFast are two different glTF implementations for Unity. They can coexist in the same project (e.g., using glTFast for import and UnityGLTF for export).

    FeatureUnityGLTFglTFast
    Primary GoalFlexibility & ExtensibilityPerformance
    StrengthsExtensive plugin support; supports non-ratified extensions (e.g., KHR_animation_pointer, KHR_audio, KHR_materials_variants)Leverages Unity-specific features like Burst and Jobs; better HDRP support
    ImplementationPure C# (no native dependencies); works on all platforms including WebGLOptimized for performance via Unity-specific tech

    Note on Import Precedence: If both are present in a project, glTFast import has precedence. You can switch between importers using a dropdown in the editor.

  6. Unity Version and Render Pipeline Compatibility

    main

    UnityGLTF is designed for modern Unity versions and specific render pipelines.

    • Unity Versions: LTS versions are strongly recommended (2021.3+, 2022.3+, or 6000.0+).
    • Color Space: Linear colorspace.
    • Render Pipelines: Universal Render Pipeline (URP) and Built-In Render Pipeline (BiRP).

    Compatibility Notes

    • HDRP: Support is currently limited and not actively maintained.
    • Legacy Unity (2020.3): If you must use Unity 2020.3, use an older version of UnityGLTF (version 2.9.1-rc or earlier).
    • Non-LTS Versions: Issues on non-LTS versions are unlikely to be addressed.
  7. Use the correct shaders for UnityGLTF materials

    main

    This file is outdated. For modern UnityGLTF usage, do not use the Unity Standard or Standard (Specular setup) shaders. Instead, use the following shaders for your materials:

    • UnityGLTF/PBRGraph
    • UnityGLTF/UnlitGraph

    UnityGLTF includes the necessary Shader Variant Collections to ensure all shader features work correctly at runtime when using these shaders.

  8. Export animations from the Editor

    main

    You can export animations in the Unity Editor using several methods:

    • Animator Controller: Exports entire Animators and their clips as glTF files with multiple animations. Clips are named after each Motion State. The 'speed' property of each Motion is baked into the clip (ensure speed is 1 for unchanged exports). Supports Humanoid (baked onto target rig) and Generic animations.
    • Legacy Animation Component: Supports exporting animation components and legacy clips (Editor only).
    • Timeline: Use GltfRecorderTrack and one or more GltfRecorderClips to record Timelines or specific sections. This uses the GLTFRecorder API internally.
  9. Record and export animations at runtime using GLTFRecorder

    main

    To create or record animations at runtime, use the GLTFRecorder API. This allows capturing the state of entire hierarchies and complex animations, exporting them directly as glTF files. It optionally supports KHR_animation_pointer for animating arbitrary properties like materials or script components.

    For a practical implementation, refer to the GLTFRecorderComponent in the project.

  10. Install UnityGLTF via Unity Package Manager (UPM)

    main

    You can install UnityGLTF directly from GitHub using the Unity Package Manager. This method is compatible with UPM.

    1. Open Window > Package Manager in Unity.
    2. Click the + button.
    3. Select Add Package from git URL.
    4. Paste the repository URL.
    5. Click Add.

    To target a specific version, append #release/<tag> to the URL.

    https://github.com/KhronosGroup/UnityGLTF.git
  11. Configure shaders for glTF builds

    main

    To prevent shaders from missing in your build, you must add the appropriate shader variant collection to your project settings:

    1. Go to Project Settings > Graphics > Preloaded Shaders.
    2. Add UnityGLTFShaderVariantCollection (or UnityGLTFShaderVariantCollection-BiRP for the Built-In Render Pipeline).

    Optimization Tips:

    • For mobile platforms, you can create your own custom Shader Variant Collection to reduce shader size.
    • You can strip additional shader variants under Project Settings > UnityGltf > Build to reduce compile time.
  12. Configure refractive materials (Transmission and Volume)

    main

    To render materials like glass (transmission) or colored jelly (volume/attenuation) using UnityGLTF/PBRGraph, follow these steps:

    1. Material Setup

    • On the UnityGLTF/PBRGraph material, check Enable Transmission.
    • Optionally check Enable Volume.
    • Adjust Transmission, Thickness, Index of Refraction, and Attenuation values.

    2. Render Pipeline Setup

    Depending on your pipeline, you must add specific features to see these effects:

    Universal Render Pipeline (URP)

    • Select your URP Renderer Asset.
    • In the Renderer Features section, add an Opaque Texture (Rough Refraction) feature.

    Built-In Render Pipeline

    • Add the RoughRefraction component to your Main Camera.

    High Definition Render Pipeline (HDRP)

    • HDRP has its own rough refraction support. There is currently no automatic import/export support to convert to HDRP shaders. Use glTFast if you require this workflow.