一、使用场景
在导入材质贴图时,往往需要把法线贴图的Texture Type 设置为 Normal Map,金属和光滑度贴图,需要取消勾选sRGB。
二、需要用到的函数
AssetPostprocessor 允许您挂接到导入管线并在导入资源前后运行脚本。
OnPreprocessTexture 将此函数添加到一个子类中,以在纹理导入器运行之前获取通知。
官方文档链接: https://docs.unity.cn/cn/current/ScriptReference/AssetPostprocessor.html
三、代码
using System.IO;
using UnityEditor;
using UnityEngine;
class AutoSetTextureType: AssetPostprocessor
{
// 在纹理导入器运行之前获取通知
void OnPreprocessTexture()
{
//判断文件类型
if (assetPath.EndsWith(".png"))
{
string fileName = Path.GetFileNameWithoutExtension(assetPath);
TextureImporter importer = assetImporter as TextureImporter;
if (fileName.EndsWith("_Normal"))
{
if (importer != null)
{
// 设置纹理类型为 Normal Map
importer.textureType = TextureImporterType.NormalMap;
应用更改
AssetDatabase.ImportAsset(assetPath, ImportAssetOptions.ForceUpdate);
}
}
else if (fileName.EndsWith("_Metallic") || fileName.EndsWith("_Roughness"))
{
if (importer != null)
{
importer.sRGBTexture = false;
AssetDatabase.ImportAsset(assetPath, ImportAssetOptions.ForceUpdate);
}
}
}
}
}
四、使用方法
脚本放在Editor文件夹下,导入纹理贴图时会自动更改设置
五、补充
OnPreprocessTexture 在更改Texture资源设置时也会调用,这是因为当你修改了纹理资源后,Unity 编辑器会重新导入(reimport)这个纹理,这个过程会触发 OnPreprocessTexture 函数。提供一个方法规避此问题,给资源做标记。
public class MyTextureProcessor : AssetPostprocessor
{
void OnPreprocessTexture()
{
// 获取当前处理的纹理对象
TextureImporter importer = assetImporter as TextureImporter;
// 检查是否已经处理过
if (importer.userData.Contains("Processed"))
{
Debug.Log("Texture has already been processed: " + assetPath);
return;
}
// 应用预处理
importer.npotScale = TextureImportNPOTScale.None;
importer.filterMode = FilterMode.Bilinear;
importer.Apply();
// 标记为已处理
importer.userData = "Processed";
importer.Apply();
}
}