You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Runtime加载StreamingAssets纹理 修改导入设置遇TextureImporter空引用

问题:Runtime加载StreamingAssets纹理时TextureImporter返回null

我在模组开发中需要从StreamingAssets文件夹加载纹理并修改其导入设置(无法使用Resources文件夹),但编写的方法里TextureImporter始终返回null:

private Texture2D LoadTexture(string filePath, bool normal)
{
        Texture2D texture = new Texture2D(2, 2);
        byte[] imageData = System.IO.File.ReadAllBytes(filePath);
        texture.LoadImage(imageData);

        TextureImporter textureImporter = AssetImporter.GetAtPath(filePath) as TextureImporter;

        if (normal)
            textureImporter.textureType = TextureImporterType.NormalMap;
        else
            textureImporter.textureType = TextureImporterType.Default;

        textureImporter.wrapMode = TextureWrapMode.Repeat;
        textureImporter.mipmapEnabled = true;
        AssetDatabase.ImportAsset(filePath);

        return texture;
}

核心原因

  1. 路径错误:AssetImporter.GetAtPath仅接受Unity项目内的相对路径(例如Assets/StreamingAssets/xxx.png),而你在Runtime使用的是系统绝对路径,因此无法找到对应的资源导入器。
  2. API限制:TextureImporter、AssetDatabase都是编辑器专属API,只能在Unity编辑器环境中运行,打包后的Runtime环境完全无法调用这些类,强行调用会直接返回null或报错。

解决方案

情况1:在Editor环境预处理模组资源

如果你的模组需要在编辑器阶段预先配置纹理导入设置,使用项目相对路径即可:

// 注意:此代码仅能在Unity编辑器中运行
private void PreprocessTextureInEditor(string relativePath, bool isNormalMap)
{
    TextureImporter textureImporter = AssetImporter.GetAtPath(relativePath) as TextureImporter;
    if (textureImporter == null)
    {
        Debug.LogError("找不到对应纹理的导入器,请检查路径是否为项目相对路径");
        return;
    }

    textureImporter.textureType = isNormalMap ? TextureImporterType.NormalMap : TextureImporterType.Default;
    textureImporter.wrapMode = TextureWrapMode.Repeat;
    textureImporter.mipmapEnabled = true;
    // 应用修改并重新导入
    textureImporter.SaveAndReimport();
}

调用示例:PreprocessTextureInEditor("Assets/StreamingAssets/MyTexture.png", true);

情况2:Runtime加载时模拟导入设置效果

Runtime环境无法修改导入设置,只能在加载纹理后直接调整Texture2D的属性:

private Texture2D LoadTextureAtRuntime(string filePath, bool isNormalMap)
{
    byte[] imageData = System.IO.File.ReadAllBytes(filePath);
    // 创建带mipmap的纹理(第三个参数true表示启用mipmap)
    Texture2D texture = new Texture2D(2, 2, TextureFormat.RGBA32, true);
    // 加载图像数据
    texture.LoadImage(imageData);

    // 设置WrapMode
    texture.wrapMode = TextureWrapMode.Repeat;

    // 模拟法线图效果(Unity 2020+支持)
    if (isNormalMap)
    {
        texture.ConvertToNormalMap();
    }

    // 生成并应用mipmap
    texture.GenerateMips();
    texture.Apply();

    return texture;
}

额外建议

模组开发中如果需要保留纹理的导入设置,建议在Editor阶段将纹理打包为AssetBundle,Runtime加载AssetBundle即可直接获取配置好的纹理,无需手动调整属性。

内容的提问来源于stack exchange,提问作者Lotous21

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 12:57:51