在运行时加载纹理并更改纹理导入设置

问题描述 投票:0回答:1

我试图在运行时从 StreamingAssets 文件夹加载纹理,而不是更改它们的导入设置。

不能使用资源,因为这将用于改装目的

我编写了以下方法,但由于某种原因,纹理导入器总是返回 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;
}
c# unity3d
1个回答
0
投票

AssetImporter
是一个编辑器类,因此您不能在运行时使用它。要在运行时加载图像,您只需选择合适的纹理格式并接下来调用
LoadImage
。通常法线贴图使用压缩格式并且在线性颜色空间中。

private Texture2D LoadTexture(string filePath, bool normal)
{
    Texture2D texture;
    
    if(normal)
    {
        texture = new Texture2D(2, 2, TextureFormat.DXT1, mipChain: true, linear: true);
    }
    else
    {
        texture = new Texture2D(2, 2);
    }

    byte[] imageData = System.IO.File.ReadAllBytes(filePath);
    texture.LoadImage(imageData);
    return texture;
}

当然这也不一定,这里只是举个例子。您可以根据您的实际图像填写这些参数。您最好将参数更改为

format
linear
以获得更好的兼容性。

private Texture2D LoadTexture(string filePath, TextureFormat format, bool linear)
{
    Texture2D texture = new Texture2D(2, 2, format, true, linear);
    byte[] imageData = System.IO.File.ReadAllBytes(filePath);
    texture.LoadImage(imageData);
    return texture;
}
© www.soinside.com 2019 - 2024. All rights reserved.