Siccity / GLTFUtility

Simple GLTF importer for Unity
MIT License
998 stars 219 forks source link

Invalid AssetDatabase path: Use path relative to the project folder. #122

Open udvaritibor opened 3 years ago

udvaritibor commented 3 years ago

I'm trying to load a glTF file from the application's AppData folder by using the absolute path.

This is the warning I get for all the assets:

Invalid AssetDatabase path: C:\Users\xyz\AppData\LocalLow\asd\asd.jpeg. Use path relative to the project folder.

How could I fix this warning? I can't really convert the AppData folder's path to a path relative to the project folder, or can I?

Thanks in advance!

AkagawaTsurunaki commented 3 months ago

My solution is to use URI instead of absolute path.

The reason is that method UnityEditor.AssetDatabase.LoadAssetAtPath constraints that all paths must be relative to the project folder, for example: Assets/MyTextures/hello.png. But if we use URI, for example: File://C:/Users/xyz/AppData/LocalLow/asd/asd.jpeg, in your case, that will be OK.

So I edited the code from line 38 in Siccity.GLTFUtility.GLTFImage.cs:

public IEnumerator CreateTextureAsync(bool linear, Action<Texture2D> onFinish, Action<float> onProgress = null) {
    if (!string.IsNullOrEmpty(path)) {
#if UNITY_EDITOR
        // Load textures from asset database if we can
        if (UnityEditor.AssetDatabase.AssetPathExists(path))
        {
            Texture2D assetTexture = UnityEditor.AssetDatabase.LoadAssetAtPath(path, typeof(Texture2D)) as Texture2D;
            if (assetTexture != null) {
                onFinish(assetTexture);
                if (onProgress != null) onProgress(1f);
                yield break;
            }
        }
        else
        {
            // If we can not load textures from asset database,
            // we should load it from UnityWebRequest.
            path = "File://" + path.Replace("\\", "/").Trim();
        }

#endif
    ...

Before I load texture from absolute path, I will check whether the path is a valid asset path for Unity. If true, then execute the original code snippet. If false, I will change the absolute path to URI, which will let the code try to load texture from URI.

Note:

  1. The warning WILL NOT disappear because I called method UnityEditor.AssetDatabase.AssetPathExists before.
  2. I just tested it on Windows platform and it loads GLTF well. Seem that Android and IOS platform will transform absolute path to URI while Windows will not in this method.

Also see:

[Error loading texture from disk · Issue #79 · Siccity/GLTFUtility (github.com)](https://github.com/Siccity/GLTFUtility/issues/79)

[Unity - Scripting API: AssetDatabase.LoadAssetAtPath (unity3d.com)](https://docs.unity3d.com/ScriptReference/AssetDatabase.LoadAssetAtPath.html)

[Load Texture at Run time from file - Questions & Answers - Unity Discussions](https://discussions.unity.com/t/load-texture-at-run-time-from-file/2667/2)