docs.unity3d.com
Search Results for

    Show / Hide Table of Contents

    Use case: Use glTFast Add-on API

    This use case describes the steps to use glTFast Add-on API to import custom data from the extras property of a glTF™ JSON object. This example uses Newtonsoft JSON parser to deserialize data.

    To accomplish this use case, do the following:

    1. Add custom data in a glTF asset
    2. Create a custom glTF import behavior
    3. Add assembly definitions
    4. Set up a new scene
    5. Import the glTF asset in runtime

    Before you start

    Before you start, you must add the following package dependencies to your project.

    • In the manifest.json file, add the following dependencies:
      {
        "dependencies": {
          // Add these lines:
          // Replace "<x.y.z>" with the version you wish to install
          "com.unity.cloud.gltfast": "<x.y.z>",
          "com.unity.nuget.newtonsoft-json": "<x.y.z>"
          // Other dependencies...
        }
      }
    

    How do I...?

    Add custom data in a glTF asset

    Add some custom data in the extras property of a glTF JSON object:

      "nodes": [
        {
          // Example of mesh data in a glTF
          "mesh": 0,
          "name": "Cube",
    
          // Add these lines:
          "extras": {
            "some-extra-key": "some-extra-value"
          }
        }
      ]
    

    Create a custom glTF import behavior

    To create a custom glTF import behavior, follow these steps:

    1. Open your Unity® Project.
    2. Go to the Assets folder in the Project window.
    3. Select and hold Create.
    4. Select C# Script.
    5. Rename the new script as CustomGltfImport.
    6. Open the CustomGltfImport script and replace the content with the following:
      using GLTFast;
      using GLTFast.Addons;
      using System;
      using System.Threading.Tasks;
      using UnityEngine;
      using GltfImport = GLTFast.Newtonsoft.GltfImport;
      
      public class CustomGltfImport : MonoBehaviour
      {
          // Path to the gltf asset to be imported
          public string Uri;
      
          async Task Start()
          {
              try
              {
                  ImportAddonRegistry.RegisterImportAddon(new MyAddon());
                  var gltfImport = new GltfImport();
                  await gltfImport.Load(Uri);
                  await gltfImport.InstantiateMainSceneAsync(transform);
              }
              catch (Exception e)
              {
                  Debug.LogException(e);
              }
          }
      
          public class MyAddon : ImportAddon<MyAddonInstance> { }
          public class MyAddonInstance : ImportAddonInstance
          {
              GltfImport m_GltfImport;
      
              public override void Dispose() { }
      
              public override void Inject(GltfImportBase gltfImport)
              {
                  var newtonsoftGltfImport = gltfImport as GltfImport;
                  if (newtonsoftGltfImport == null)
                      return;
      
                  m_GltfImport = newtonsoftGltfImport;
                  newtonsoftGltfImport.AddImportAddonInstance(this);
              }
      
              public override void Inject(IInstantiator instantiator)
              {
                  var goInstantiator = instantiator as GameObjectInstantiator;
                  if (goInstantiator == null)
                      return;
                  var _ = new MyInstantiatorAddon(m_GltfImport, goInstantiator);
              }
      
              public override bool SupportsGltfExtension(string extensionName)
              {
                  return false;
              }
          }
      }
      
      public class MyInstantiatorAddon
      {
          GltfImport m_GltfImport;
          GameObjectInstantiator m_Instantiator;
      
          public MyInstantiatorAddon(GltfImport gltfImport, GameObjectInstantiator instantiator)
          {
              m_GltfImport = gltfImport;
              m_Instantiator = instantiator;
              m_Instantiator.NodeCreated += OnNodeCreated;
              m_Instantiator.EndSceneCompleted += () =>
              {
                  m_Instantiator.NodeCreated -= OnNodeCreated;
              };
          }
      
          void OnNodeCreated(uint nodeIndex, GameObject gameObject)
          {
              // De-serialize glTF JSON
              var gltf = m_GltfImport.GetSourceRoot();
      
              var node = gltf.Nodes[(int)nodeIndex] as GLTFast.Newtonsoft.Schema.Node;
              var extras = node.extras;
      
              if (extras == null)
                  return;
      
              // Access values in the extras property
              if (extras.TryGetValue("some-extra-key", out string extraValue))
              {
                  var component = gameObject.AddComponent<ExtraData>();
                  component.someExtraKey = extraValue;
              }
          }
      }
      
    7. Repeat step 2-4 to create another new script
    8. Rename the new script as ExtraData.
    9. Open the ExtraData script and replace the content with the following:
      using UnityEngine;
      
      class ExtraData : MonoBehaviour
      {
          public string someExtraKey;
      }
      
      

    Add assembly definitions

    In your assembly definition file (.asmdef file), add the following references:

      "references": [
        // Add these lines:
        "glTFast",
        "glTFast.Newtonsoft"
        // Other references...
      ]
    

    Set up a new scene

    To set up a new scene, follow these steps:

    1. Create a new scene.
    2. Create a GameObject called GltfImport.
    3. Select Add Component in the Inspector window and add the Custom Gltf Import component.
    4. In the Uri field, set the path to point to where the glTF asset is stored.

    Import the glTF asset in runtime

    Select Play, the glTF asset should be loaded and displayed at runtime.

    You can verify that the custom data in the extras property of the glTF is imported correctly by inspecting the loaded glTF asset: Screen capture that displays the extra data in the imported glTF asset

    Trademarks

    Unity® is a registered trademark of Unity Technologies.

    glTF™ is a trademark of The Khronos Group Inc.

    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)