KhronosGroup / UnityGLTF

Runtime glTF 2.0 Loader for Unity3D
MIT License
1.84k stars 490 forks source link

load glb files in editor time #797

Open Singh-sid930 opened 2 weeks ago

Singh-sid930 commented 2 weeks ago

Hi, I have glb files in local folders within the Asset directory that I would like to load during editor time by using a custom button and text field. Is that possible through the importer ?

hybridherbst commented 2 weeks ago

Can you add a bit more info on what you want to do? If you put the GLB files into your project they will be imported by UnityGTLF through Unity's regular import pipeline. No code needed.

Singh-sid930 commented 2 weeks ago

As a minimal example :

public class GlbLoader : EditorWindow
  {
    private string filePath = "Asset/path/tp/glbFile.glb"; // Default JSON file name

    [MenuItem("Custom/Load glb file")]
    public static void ShowWindow()
    {
      EditorWindow.GetWindow(typeof(GlbLoader));
    }

    private void OnGUI()
    {
      GUILayout.Label("Load Procedural Data", EditorStyles.boldLabel);
      filePath = EditorGUILayout.TextField("Asset file path:", filePath);

      if (GUILayout.Button("Load Data"))
      {
        LoadGlbFile(filePath);
      }
    }

    private void LoadGlbFile(string assetPath){
     // code here to load the glb asset, instantiate it as a child GameObject of a parent GameObject
     // Spawn the glb asset GameObject in the Editor. 
     // I further process this to save the the Parent Gameobject as a prefab. 
    }
}
Singh-sid930 commented 2 weeks ago

I want to fill out the LoadGlbFile function to be able to spawn the glb asset as a gameObject

hybridherbst commented 2 weeks ago

It seems that what you're actually trying to do is add components and so on to the objects already imported via the editor importer?

The recommended way would be using an import plugin (from UnityGLTF), which allows you to modify what is imported by the ScriptedImporter directly.

If your file is really in Assets and you want to create a prefab variant from it, then it would be like this:

private void LoadGlbFile(string assetPath)
{
    GameObject newObject = PrefabUtility.InstantiatePrefab(AssetDatabase.LoadAssetAtPath<GameObject>(path)) as GameObject;
    newObject.AddComponent<SphereCollider>(); // example for modification
    newObject.name = selected.name + " Variant";
    PrefabUtility.SaveAsPrefabAsset(newObject, "Assets/" + newObject.name + "_variant" + ".prefab");
    DestroyImmediate(newObject);
}