gltfAssetPostprocessor.cs
2.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
using System;
using System.IO;
using UnityEditor;
using UnityEngine;
namespace UniGLTF
{
public class gltfAssetPostprocessor : AssetPostprocessor
{
static void OnPostprocessAllAssets(string[] importedAssets,
string[] deletedAssets,
string[] movedAssets,
string[] movedFromAssetPaths)
{
foreach (string path in importedAssets)
{
if (UnityPath.FromUnityPath(path).IsStreamingAsset)
{
Debug.LogFormat("Skip StreamingAssets: {0}", path);
continue;
}
var ext = Path.GetExtension(path).ToLower();
switch (ext)
{
case ".gltf":
case ".glb":
{
var gltfPath = UnityPath.FromUnityPath(path);
var prefabPath = gltfPath.Parent.Child(gltfPath.FileNameWithoutExtension + ".prefab");
ImportAsset(UnityPath.FromUnityPath(path).FullPath, ext, prefabPath);
break;
}
}
}
}
public static void ImportAsset(string src, string ext, UnityPath prefabPath)
{
if (!prefabPath.IsUnderAssetsFolder)
{
Debug.LogWarningFormat("out of asset path: {0}", prefabPath);
return;
}
var context = new ImporterContext();
context.Parse(src);
// Extract textures to assets folder
context.ExtranctImages(prefabPath);
ImportDelayed(src, prefabPath, context);
}
static void ImportDelayed(string src, UnityPath prefabPath, ImporterContext context)
{
EditorApplication.delayCall += () =>
{
//
// After textures imported(To ensure TextureImporter be accessible).
//
try
{
context.Load();
context.SaveAsAsset(prefabPath);
context.EditorDestroyRoot();
}
catch (UniGLTFNotSupportedException ex)
{
Debug.LogWarningFormat("{0}: {1}",
src,
ex.Message
);
context.EditorDestroyRootAndAssets();
}
catch (Exception ex)
{
Debug.LogErrorFormat("import error: {0}", src);
Debug.LogErrorFormat("{0}", ex);
context.EditorDestroyRootAndAssets();
}
};
}
}
}