3.4 编辑器脚本化:蓝图与 Python 两条路
两条路线对比
| 蓝图编辑器脚本 | Python | |
|---|---|---|
| 上手 | 可视化拖拽 | 写代码(但 UE API 简单) |
| 速度 | 中(蓝图虚拟机) | 快(直接调 C++ 绑定) |
| 字符串/数学/循环 | 弱 | 强 |
| 版本管理 | 资产文件,diff 不友好 | 文本,git 友好 |
| 策划可改 | 强 | 弱(看不懂) |
| 适合 | 交互工具、简单处理 | 批处理、复杂逻辑、CI |
官方总览:「编辑器的脚本与自动化」(https://www.wanxiangyundang.top/read/unreal-engine-5-8-docs/scripting-and-automating-the-u-0a4d)。
蓝图脚本能力的范围
UE5 的蓝图编辑器脚本(「使用蓝图编写编辑器脚本」https://www.wanxiangyundang.top/read/unreal-engine-5-8-docs/scripting-the-unreal-editor-us-e9f2)开放了大量编辑器能力:
- Editor Utility Library(选中资产、当前关卡、世界工具)
- Editor Scripting / Asset(加载、保存、重命名、导入导出)
- Asset Registry 查询
- Spawn/删除 Actor、改关卡
- Subsystem(Editor Utility Subsystem 的 Task、Notification)
「蓝图做不了」的场景基本只剩:复杂文本处理、性能敏感循环、文件系统操作、自动化流水线——这些上 Python。
Python 脚本
启用:项目设置 → 插件 → Python Editor Script Plugin(默认开启,企业版才有…UE5 默认启用)。「使用 Python 脚本化运行虚幻编辑器」(https://www.wanxiangyundang.top/read/unreal-engine-5-8-docs/scripting-the-unreal-editor-us-327f)。
import unreal
# 查询所有数据资产
ar = unreal.AssetRegistryHelpers.get_asset_registry()
filter = unreal.ARFilter(
package_paths=["/Game/Items"],
class_names=["PrimaryDataAsset"],
recursive_paths=True)
assets = ar.get_assets(filter)
# 批量改属性并保存
for ad in assets:
asset = ad.get_asset()
if hasattr(asset, 'damage'):
asset.damage += 5
unreal.EditorAssetLibrary.save_asset(asset.get_path_name())
unreal.log("Processed %d assets" % len(assets))
Python 环境特点:
- 跑在主线程(游戏线程)——慢操作会卡编辑器
- API 是
unreal.XXX形式的 Sphinx 绑定,和 C++ 名字几乎一致 - 脚本可放
Content/Python/目录自动加入搜索路径
长任务:进度条与分帧
几千个资产的处理:
total = len(assets)
for i, ad in enumerate(assets):
unreal.EditorAssetUtils... #
if i % 100 == 0:
unreal.log("Progress: %d/%d" % (i, total))
卡超过几秒就考虑分拆:Python 里用 unreal.EditorScriptingUtils 的 SlowTask 或把任务切片用定时器跑。重度批处理推荐最终上 C++(AsyncTask + FScopedSlowTask)。
脚本的入口
- 控制台:
py filename直接跑 - 编辑器启动:
StartupScript(编辑器偏好里的 Python 启动脚本) - 按钮:EUW 里 Execute Python Command 节点
- CI:命令行
-ExecPythonScript=xxx.py(第五章)
混合策略:UI 蓝图 + 逻辑 Python
我团队最常用的组合:
EUW 界面(按钮、输入框、列表)
↓ Execute Python Command
Python 脚本(批处理 + 校验 + 日志)
↓ Return Value(字符串)
界面显示结果
蓝图管交互、Python 管「脏活」——职责清晰,改逻辑不动 UI,改 UI 不动逻辑。
一个坑:脚本的路径
Python 脚本里写文件路径:UE5 的 Python 工作目录不固定,用 unreal.SystemLibrary.get_project_directory() 这类函数取绝对路径,相对路径容易找不到。
心得:把「常用 Python 脚本」维护成一个目录:
Tools/Python/,每个文件头部写清楚用法(一行注释)。半年后你自己也会忘记脚本怎么用——有文档注释的脚本资产和没文档的,完全两个东西。
