unity材质球自动遍历所需贴图
一、原理
例如一个材质球名为:decal_text_cranes_01_mat ,
然后从全局遍历出:decal_text_cranes_01_albedo赋值给材质球的basemap,
全局遍历出decal_text_cranes_01_maods 赋值给材质球metallicmap通道,
全局遍历出decal_text_cranes_01_normal 给材质球normalmap通道,
**规律:**材质球名字:decal_text_cranes_01_mat 把后面mat换成通道名称,就是该材质球的通道贴图
二、用法
1.代码:
using unityengine;
using system.collections.generic;
using system.io;
using unityeditor;
public class autoassigntexturemaps : monobehaviour
{
public list<material> targetmaterials; // 在inspector中指定目标材质列表
private dictionary<string, string> texturemapnames = new dictionary<string, string>
{
{ "albedo", "_basemap" }, // base color
{ "maods", "_metallicglossmap" }, // metallic and smoothness
{ "normal", "_bumpmap" } // normal map
};
[contextmenu("_alphamat后缀自动补全")]
void assigntextures1( )
{
foreach (material material in targetmaterials)
{
string basename = material.name.replace("_alphamat", "");
foreach (var pair in texturemapnames)
{
string texturename = basename + "_" + pair.key;
texture2d texture = findtexture(texturename);
if (texture != null)
{
material.settexture(pair.value, texture);
debug.log($"assigned {texturename} to {pair.value} for material {material.name}");
}
else
{
debug.logerror($"could not find texture {texturename} for material {material.name}");
}
}
}
}
[contextmenu("_mat后缀自动补全")]
void assigntextures2( )
{
foreach (material material in targetmaterials)
{
string basename = material.name.replace("_mat", "");
foreach (var pair in texturemapnames)
{
string texturename = basename + "_" + pair.key;
texture2d texture = findtexture(texturename);
if (texture != null)
{
material.settexture(pair.value, texture);
debug.log($"assigned {texturename} to {pair.value} for material {material.name}");
}
else
{
debug.logerror($"could not find texture {texturename} for material {material.name}");
}
}
}
}
texture2d findtexture(string texturename)
{
string[] guids = assetdatabase.findassets(texturename);
if (guids.length > 0)
{
string assetpath = assetdatabase.guidtoassetpath(guids[0]);
return assetdatabase.loadassetatpath<texture2d>(assetpath);
}
return null;
}
}
2.使用方法
1.将脚本挂载到一个空物体:
2.把所需的材质球添加到集合列表中。
3.点右上角三个点,进行调用脚本中的方法。
发表评论