【问题标题】:How to get the path and file size of Unity built-in assets?如何获取 Unity 内置资源的路径和文件大小?
【发布时间】:2019-05-16 00:59:43
【问题描述】:

背景

目前,我正在编写一个自定义 Unity 编辑器插件,允许用户将选定的图像文件上传到云中的 REST API 端点进行处理(例如添加转换、优化等)。

它还显示了所选图像的一系列前后细节(例如,图像宽度/高度/大小之前与图像宽度/高度/大小之后)

用户通过以下代码选择想要的图片

selected_texture = (Texture2D) EditorGUI.ObjectField(drawing_rect, selected_texture, typeof(Texture2D), false);

选择后,我可以通过以下方式获取相应的文件大小

file_size = new FileInfo(AssetDatabase.GetAssetPath(selected_texture)).Length;

问题

这适用于大多数选定的纹理,但是当我选择内置 Unity 纹理时,我收到以下错误。

FileNotFoundException: Could not find file 'Resources/unity_builtin_extra'

【问题讨论】:

    标签: unity3d


    【解决方案1】:

    Unity 中有两个内置的资源库:

    1. “Resources/unity_builtin_extra”中的BuiltIn-Library:包含UGUI sprite、Default-Material、Shader等。
    2. “Library/unity 默认资源”中的BuiltIn-Library:包含内置的 3D 网格和 OnGUI 资产。

    如果你使用 AssetDatabase.GetAssetPath,你总是会得到上面的一个或另一个路径。

    要解决此问题,您需要执行以下代码:

    public const string BuiltinResources = "Resources/unity_builtin_extra";
    public const string BuiltinExtraResources = "Library/unity default resources";
    
    public static bool IsBuiltInAsset(string assetPath)
    {
        return assetPath.Equals(BuiltinResources) || assetPath.Equals(BuiltinExtraResources);
    }
    
    public static long GetTextureFileLength(Texture texture)
    {
        string texturePath = AssetDatabase.GetAssetPath(texture);
        if (IsBuiltInAsset(texturePath))
        {
            /*
                * You can get all built-in assets by this way.
                * 
            var allAssets = AssetDatabase.LoadAllAssetsAtPath(BuiltinResources);
            var allExtraAssets = AssetDatabase.LoadAllAssetsAtPath(BuiltinExtraResources);
            */
    
            // not supportted
            // return -1;
    
            // using MemorySize
            return Profiler.GetRuntimeMemorySizeLong(texture);
        }
        else
        {
            return new FileInfo(texturePath).Length;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-09-09
      • 1970-01-01
      • 2020-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-09
      • 1970-01-01
      • 2011-08-28
      相关资源
      最近更新 更多