Unity MCP 程序化纹理生成实战:manage_texture 工具 8 大动作与 TextureImporter 配置全解析
【免费下载链接】unity-mcpUnity MCP acts as a bridge between AI assistants and your Unity Editor. Give your LLM tools to manage assets, control scenes, edit scripts, and automate tasks within Unity.项目地址: https://gitcode.com/GitHub_Trending/un/unity-mcp
导读
manage_texture是 Unity MCP 中归属于vfx组的纹理管理工具,它允许 AI 助手通过 MCP 协议在 Unity 编辑器中直接生成、修改和删除纹理资源:既可以创建纯色填充、棋盘格、条纹、圆点、网格、砖墙等程序化图案,也可以生成线性/径向渐变与 Perlin 噪声,还能导入本地图片、按像素区域改写纹理,并一键配置 Sprite、法线贴图等导入设置。读完本文,你将掌握该工具全部 8 个动作的参数语义、颜色归一化规则、底层算法原理以及命令行(CLI)用法,能够在 AI 工作流中稳定地自动化批量生成 UI 占位图、程序化贴图与 Sprite 资源。
一、工具概览:从 MCP 参数到 Unity 像素
manage_texture的官方描述(见 服务端工具注册)将其定位为:
Procedural texture generation for Unity. Creates textures with solid fills, patterns (checkerboard, stripes, dots, grid, brick), gradients, and noise.
它共提供 8 种动作:create、modify、delete、create_sprite、apply_pattern、apply_gradient、apply_noise、set_import_settings。该动作白名单在 Unity 端 ManageTexture.cs 中被硬编码校验,未知动作会直接返回错误信息并列出合法动作列表。
从架构上看,该工具是一条完整的调用链:
- AI 客户端向 Python MCP 服务端发起
manage_texture调用; - 服务端 manage_texture.py 先执行参数归一化与合法性校验,再通过
send_with_unity_instance/async_send_command_with_retry把参数(snake_case 已转换为 camelCase)转发给指定 Unity 实例; - Unity 端 ManageTexture.cs 的
HandleCommand按action分发到具体实现,操作Texture2D并调用AssetDatabase落盘导入; - 底层像素级操作由 TextureOps.cs 提供(填充、像素写入、PNG/JPG 编码等)。
值得注意的是,该工具在 Unity 端注册时带有AutoRegister = false(ManageTexture.cs),即不会自动注册为 Unity 侧独立命令,而是由 Python 服务端显式调度;同时在服务端注册时标注了destructiveHint=True(manage_texture.py),提示客户端delete属于破坏性操作。
二、参数参考:完整参数表与校验规则
下表完整列出该工具的全部参数(继承自 官方参数文档),并结合 manage_texture.py 与 ManageTexture.cs 补充了默认值与取值范围:
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
action | Literal['create','modify','delete','create_sprite','apply_pattern','apply_gradient','apply_noise','set_import_settings'] | 是 | 要执行的动作 |
path | str \| None | 否* | 输出纹理路径,如'Assets/Textures/MyTexture.png'(create/modify/delete/apply_/set_import_settings 均要求提供) |
width | int \| None | 否 | 纹理宽(像素),默认64,必须为正整数 |
height | int \| None | 否 | 纹理高(像素),默认64,必须为正整数 |
fill_color | list[int\|float] \| dict \| str \| None | 否 | 填充色:[r,g,b]/[r,g,b,a]数组、{r,g,b,a}对象或十六进制字符串;同时支持 0-255(如[255,0,0])与 0.0-1.0 归一化(如[1.0,0,0])两种区间 |
pattern | Literal['checkerboard','stripes','stripes_h','stripes_v','stripes_diag','dots','grid','brick'] \| None | 否 | apply_pattern/create使用的图案类型 |
palette | list[list[int\|float]] \| str \| None | 否 | 调色板,格式[[r,g,b,a],...],同样支持 0-255 与 0.0-1.0 双区间;可用于图案与渐变 |
pattern_size | int \| None | 否 | 图案单元尺寸(像素),默认8,必须大于 0 |
pixels | list[list[int]] \| str \| None | 否 | 直接像素数据:[r,g,b,a]的 JSON 数组(数量必须等于width*height)或 base64 字符串 |
image_path | str \| None | 否 | 源图片路径(PNG/JPG),仅create/create_sprite可用 |
gradient_type | Literal['linear','radial'] \| None | 否 | 渐变类型,默认linear |
gradient_angle | float \| None | 否 | 线性渐变角度(度),默认0 |
noise_scale | float \| None | 否 | 噪声缩放/频率,默认0.1 |
octaves | int \| None | 否 | 噪声八度数(细节层数),默认1,必须大于 0 |
set_pixels | dict \| None | 否 | modify动作的修改区域:{x, y, width, height, color 或 pixels} |
as_sprite | dict \| bool \| None | 否 | 配置为 Sprite:{pivot: [x,y], pixels_per_unit: 100}或true使用默认值 |
import_settings | dict \| None | 否 | TextureImporter设置字典(详见下文第五节) |
服务端对参数做了严格归一化(见 manage_texture.py):尺寸与 octaves 必须为正整数(_normalize_dimension、_normalize_positive_int);颜色统一转为 0-255 整数区间(_normalize_color_int);调色板逐项校验(_normalize_palette);像素数组长度必须与width*height严格一致(_normalize_pixels);image_path不能与fill_color/pattern/pixels混用,且仅限create/create_sprite动作(manage_texture.py)。任何校验失败都会返回{"success": false, "message": ...}而不触及 Unity。
三、动作详解:8 大动作的使用方法与底层原理
3.1 create 与 create_sprite:从零生成纹理
create是最核心的动作。其流程见 ManageTexture.cs:
- 纯色填充:指定
fill_color时,TextureOps.FillTexture以 RGBA32 格式整图填充; - 图案:指定
pattern(配合palette、pattern_size)时逐像素计算图案颜色; - 像素数据:指定
pixels时逐像素写入; - 默认行为:三者都未指定时,Unity 端创建全透明纹理;但服务端会在
create且无任何内容参数时自动补默认纯白[255,255,255,255](manage_texture.py),因此经 MCP 调用时"空参数 create"得到的是白色纹理; - 图片导入:指定
image_path时读取本地 PNG/JPG(支持绝对路径或相对项目根目录的路径),解码为Texture2D,此时width/height参数被忽略而采用图片实际尺寸。
落盘时 TextureOps.EncodeTexture 根据扩展名编码:.png用EncodeToPNG,.jpg/.jpeg用EncodeToJPG,其他或无扩展名回退为 PNG。写入后调用AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate)完成导入,并自动创建缺失的父目录(EnsureDirectoryExists,ManageTexture.cs)。
create_sprite与create的纹理生成逻辑完全相同,差异在于落盘后会把导入类型配置为 Sprite:默认 pivot(0.5, 0.5)、pixels per unit 100,可通过as_sprite字典自定义pivot与pixels_per_unit(ManageTexture.cs)。
返回值包含path、width、height、asSprite及可选的warnings数组(ManageTexture.cs)。
3.2 apply_pattern:七种图案的像素级算法
apply_pattern动作在服务端直接复用create的图案生成路径(ManageTexture.cs)。图案颜色由 GetPatternColor 逐像素计算,调色板默认黑白([白, 黑]),颜色索引超出时自动Mathf.Clamp到调色板范围内:
| 图案 | 算法逻辑 |
|---|---|
checkerboard | ((x/size) + (y/size)) % 2,棋盘格交替取调色板第 0/1 色 |
stripes/stripes_v | 竖条纹:(x/size) % palette.Count,可产生多色条纹 |
stripes_h | 横条纹:(y/size) % palette.Count |
stripes_diag | 斜条纹:((x+y)/size) % palette.Count |
dots | 以2*size为周期的圆点:(cx²+cy²) < size²/4判定是否在圆内,圆内取第 1 色 |
grid | 网格线:x % size == 0或y % size == 0时取第 1 色 |
brick | 砖墙:奇数行偏移size/2,在行缝或列缝处取第 1 色 |
实际调用时pattern参数(配合palette、pattern_size)可以直接放在create中一并使用,也可单独使用apply_pattern动作,二者等价。
3.3 apply_gradient:线性与径向渐变
apply_gradient要求path,默认 64×64,默认gradient_type为linear、gradient_angle为0(ManageTexture.cs):
- 线性渐变(ApplyLinearGradient):将像素坐标归一化到
[0,1],与角度方向向量做点积,映射到[0,1]插值参数t; - 径向渐变(ApplyRadialGradient):以纹理中心为圆心,按到中心距离与最大距离之比计算
t; - 插值:
t通过 LerpPalette 在调色板上做多段Color.Lerp;若调色板少于 2 色,默认使用黑→白渐变。
3.4 apply_noise:Perlin 噪声与多八度细节
apply_noise基于Mathf.PerlinNoise实现(ApplyPerlinNoise):
noise_scale(默认0.1)控制噪声频率,值越大细节越密;octaves(默认1)控制叠加层数,每层振幅减半、频率翻倍,形成分形细节;服务端会校验octaves > 0(manage_texture.py);- 每次生成使用
UnityEngine.Random生成 0-1000 的随机偏移,保证多次生成结果不同; - 噪声值归一化后同样经
LerpPalette映射到调色板(默认黑→白),可用于生成地形高度图、云朵遮罩、程序化草地图案等。
3.5 modify:按区域改写现有纹理
modify需要path指向已存在的纹理(通过AssetDatabase.AssetPathToGUID校验存在性,ManageTexture.cs)。两种模式(ManageTexture.cs):
- 像素区域写入:
set_pixels指定{x, y, width, height},配合color(纯色填充该矩形)或pixels(逐像素数据数组,长度须等于width*height)写入;写入会做越界裁剪(Mathf.Clamp到纹理边界); - 导入设置快速修改:仅传
import_settings时走"快路径",直接应用导入设置不触碰像素。
注意modify中set_pixels与import_settings可以同时使用,先改像素再应用导入设置。
3.6 set_import_settings:事后调整导入配置
set_import_settings用于对已存在的纹理单独修改TextureImporter配置,要求至少提供import_settings或as_sprite之一(ManageTexture.cs)。import_settings与as_sprite二者互斥,同时指定会报错(ManageTexture.cs),官方建议统一使用import_settings并设textureType='Sprite'。
3.7 delete:删除纹理资产
delete只接受path,通过AssetDatabase.DeleteAsset删除(ManageTexture.cs)。纹理不存在时返回错误,删除失败也会返回明确错误信息。
四、颜色与调色板归一化规则
fill_color、palette、set_pixels.color、pixels均接受多种颜色书写形式,由 manage_texture.py 统一归一化为 0-255 整数[r,g,b,a]:
| 输入形式 | 示例 | 归一化结果 |
|---|---|---|
| 0-255 数组 | [255, 0, 0] | [255, 0, 0, 255](缺 alpha 补 255) |
| 0.0-1.0 归一化数组 | [1.0, 0, 0] | [255, 0, 0, 255] |
| 字典对象 | {"r": 1.0, "g": 0, "b": 0, "a": 1} | [255, 0, 0, 255] |
| 十六进制字符串 | "#FF0000"/"#FF000080" | [255, 0, 0, 255]/[255, 0, 0, 128] |
归一化判定逻辑(与 CLI 端 texture.py 的_is_normalized_color一致):当数值含小数或全部落在 0/1 边界内时按 0-1 区间处理并乘 255 取整,否则按 0-255 原样处理。集成测试 test_manage_texture.py 验证了[0.0, 0.0, 1.0, 1.0]会被正确转换为[0, 0, 255, 255]。
五、import_settings 深度解析:TextureImporter 全量配置
import_settings是功能最丰富的参数,服务端将 snake_case 键转换为 camelCase 后透传给 Unity 的TextureImporter(manage_texture.py),Unity 端由 ConfigureTextureImporter 逐项应用。完整的键与合法取值如下:
| 键(snake_case) | Unity 属性 | 合法取值 |
|---|---|---|
texture_type | textureType | default、normal_map、editor_gui、sprite、cursor、cookie、lightmap、directional_lightmap、shadow_mask、single_channel |
texture_shape | textureShape | 2d、cube |
srgb | sRGBTexture | true/false |
alpha_source | alphaSource | none、from_input、from_gray_scale |
alpha_is_transparency | alphaIsTransparency | true/false |
readable | isReadable | true/false |
generate_mipmaps | mipmapEnabled | true/false |
mipmap_filter | mipmapFilter | box、kaiser |
wrap_mode/wrap_mode_u/wrap_mode_v | wrapMode/wrapModeU/wrapModeV | repeat、clamp、mirror、mirror_once |
filter_mode | filterMode | point、bilinear、trilinear |
aniso_level | anisoLevel | 整数 0-16 |
max_texture_size | maxTextureSize | 必须为32,64,128,256,512,1024,2048,4096,8192,16384之一 |
compression | textureCompression | none、low_quality、normal_quality、high_quality |
compression_crunched | crunchedCompression | true/false |
compression_quality | compressionQuality | 整数 0-100 |
sprite_mode | spriteImportMode | single、multiple、polygon |
sprite_pixels_per_unit | spritePixelsPerUnit | 数字 |
sprite_pivot | spritePivot | [x, y]二维数组 |
sprite_mesh_type | spriteMeshType | full_rect、tight |
sprite_extrude | spriteExtrude | 整数 0-32 |
服务端会对枚举值、数值范围(aniso_level0-16、compression_quality0-100、sprite_extrude0-32、max_texture_size白名单)逐一校验,非法值直接返回错误(manage_texture.py)。布尔键还兼容0/1与"true"/"false"字符串(_normalize_bool_setting)。Unity 端 TryParseEnum 会去掉_/-再做忽略大小写的枚举匹配,容错性良好。Sprite 相关的spriteMeshType与spriteExtrude通过TextureImporterSettings写入(ManageTexture.cs)。
集成测试 test_manage_texture.py 验证了{"texture_type": "sprite", "sprite_pixels_per_unit": 100, "filter_mode": "point", "wrap_mode": "clamp"}会被正确转换为 Unity 侧的{"textureType": "Sprite", "spritePixelsPerUnit": 100, "filterMode": "Point", "wrapMode": "Clamp"}。
六、CLI 命令行用法
除 MCP 协议外,同一套能力还封装为unity-mcp texture命令组(texture.py),适合本地脚本化调用:
# 创建纯色纹理(默认白色;支持十六进制与数组颜色) unity-mcp texture create Assets/Red.png --color '[255,0,0]' unity-mcp texture create Assets/Check.png --pattern checkerboard # 快速生成 Sprite(默认 100 PPU、pivot [0.5,0.5],无内容参数时默认棋盘格图案) unity-mcp texture sprite Assets/Sprites/Player.png unity-mcp texture sprite Assets/Sprites/Coin.png --pattern dots --ppu 64 --pivot '[0.5,0.5]' # 修改现有纹理:区域填色 / 逐像素写入 / 导入设置 unity-mcp texture modify Assets/Tex.png --set-pixels '{"x":0,"y":0,"width":10,"height":10,"color":[255,0,0]}' unity-mcp texture modify Assets/UI/icon.png --as-sprite unity-mcp texture modify Assets/UI/bg.png --texture-type sprite --max-size 2048 # 单独调整导入设置 unity-mcp texture set-import-settings Assets/UI/icon.png --texture-type sprite --sprite-mode single --sprite-ppu 100 # 删除纹理(默认需确认,--force 跳过) unity-mcp texture delete "Assets/Textures/Old.png" --forceCLI 端的--max-size、--compression、--texture-type、--sprite-mode等选项均使用与 MCP 相同的枚举映射与校验(texture.py),delete走confirm_destructive_action二次确认(texture.py)。
七、约束、边界与安全检查
- 维度上限:Unity 端对超出推荐上限的尺寸仅产生 warning 而非硬性报错(ValidateDimensions):
- 单边超过1024像素 → warning;
- 总像素超过1024×1024(约 1M 像素)→ warning;
- 宽度或高度非正 → 直接报错;
- 噪声工作量:
width × height × octaves超过4,000,000时产生 warning(ManageTexture.cs),避免 AI 误提交超大噪声任务卡死编辑器; - 像素数组长度:
pixels数组长度必须与width*height严格一致,否则拒绝执行并给出期望数量(manage_texture.py); - 破坏性操作提示:工具注册时带
destructiveHint=True,delete在 CLI 中需确认; - 执行前检查:服务端在每次调用前执行
preflight(ctx, wait_for_no_compile=True, refresh_if_dirty=True)(manage_texture.py),等待编译完成并在资源脏时先刷新,保证操作时编辑器处于稳定状态; - 实例路由:通过
get_unity_instance_from_context(ctx)解析目标 Unity 实例,支持多实例环境下的精确定向。
八、测试验证:参数归一化与错误处理的证据
集成测试 test_manage_texture.py 通过 mock 传输层验证了工具的参数归一化与错误处理行为:
test_create_texture_with_color_array:0-255 颜色数组原样透传(L24-L46);test_create_texture_with_normalized_color:0.0-1.0 颜色被转换为 0-255(L48-L68);test_create_sprite_with_pattern:create_sprite+checkerboard+as_sprite{pixelsPerUnit, pivot}正确组装参数(L70-L95);test_texture_modify_pixels_array:set_pixels.pixels中的归一化颜色被转换,0.5,0.5,0.5→128,128,128(L154-L189);test_texture_modify_pixels_invalid_length:像素数组长度不匹配时返回"pixels array must have 4 entries"错误(L191-L217);test_invalid_dimensions:非正尺寸被拒绝(L257-L277)。
这些测试覆盖了本文第三节至第五节描述的颜色归一化、像素校验与尺寸校验逻辑,可作为行为契约参考。
结语
manage_texture是 Unity MCP 中"生成式资产管理"的代表性工具:它把 AI 的自然语言意图翻译成像素级的确定性操作,从纯色、图案、渐变、噪声到任意像素写入全覆盖,并以import_settings打通了资源导入管线的最后一个环节。配合 ToolDiscoveryService.cs 的工具发现机制与 tools-reference.md 技能文档,AI 助手可以在一次会话中完成"生成占位纹理 → 改造成 Sprite → 调整压缩设置"的完整素材生产链路,显著减少美术资源的重复手工劳动。
【免费下载链接】unity-mcpUnity MCP acts as a bridge between AI assistants and your Unity Editor. Give your LLM tools to manage assets, control scenes, edit scripts, and automate tasks within Unity.项目地址: https://gitcode.com/GitHub_Trending/un/unity-mcp
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考