代码之家  ›  专栏  ›  技术社区  ›  FutureCake

宽高比导入的图像统一编辑器脚本不正确

  •  0
  • FutureCake  · 技术社区  · 7 年前

    我已经写了一个脚本,当我将图像导入unity时,它应该确保图像的纵横比保持不变。

    public class PostprocessImages : AssetPostprocessor
    {
        void OnPostprocessTexture(Texture2D texture)
        {
            TextureImporter textureImporter = (TextureImporter)assetImporter;
            textureImporter.npotScale = TextureImporterNPOTScale.None;
            textureImporter.mipmapEnabled = false;
        }
    }
    

    脚本位于资源中的编辑器文件夹中。 但当我导入图像时,会得到以下结果:

    enter image description here

    这绝对不是我要找的。

    enter image description here

    但是,当我转到导入图像的检查器并更改随机设置并单击“应用”时,纹理会得到正确的宽高比。以及我在代码中修改的设置。当我检查图像时是正确的。但是图像没有正确的纵横比。。
    见下图:

    enter image description here

    如何使图像具有正确的纵横比,从getgo(当我导入它时)开始。因为我不想手动操作,因为我必须导入成百上千的图像。

    如果有什么不清楚的地方,请告诉我,以便我能澄清。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Programmer    7 年前

    我没有这个问题,但可以考虑可能的解决办法。

    首先要做的是使用 OnPreprocessTexture 功能而不是 OnPostprocessTexture . 这将在导入纹理之前对其进行修改。

    public class PostprocessImages : AssetPostprocessor
    {
        void OnPreprocessTexture()
        {
            TextureImporter textureImporter = (TextureImporter)assetImporter;
            textureImporter.npotScale = TextureImporterNPOTScale.None;
            textureImporter.mipmapEnabled = false;
        }
    }
    

    TextureImporter.SaveAndReimport() 在对 Texture 这样统一在做出改变后会重新导入。这可能会解决问题。值得注意的是你需要一种方法来确保 纹理导入器。保存和导入() 纹理导入器。保存和导入() 会触发 OnPreprocessTexture() . 如果不实现一种方法来确定这一点,您将进入一个永不结束的纹理导入的无限循环。在下面的示例中,我使用了 static List

    static List<TextureImporter> importedTex = new List<TextureImporter>();
    
    void OnPostprocessTexture(Texture2D texture)
    {
        TextureImporter textureImporter = (TextureImporter)assetImporter;
    
        /*Make sure that SaveAndReimport is called once ONLY foe each TextureImporter
         There would be infinite loop if this is not done
         */
        if (!importedTex.Contains(textureImporter))
        {
            textureImporter.npotScale = TextureImporterNPOTScale.None;
            importedTex.Add(textureImporter);
            textureImporter.SaveAndReimport();
        }
    }