
在上一次的分享中我们介绍unreal中的python使用,此处应该有链接Python | Unreal中的python开发,今天我们来实际操作在引擎里面试用一下。
首先我们来实现一个简单的小功能,用python将外部的文件导入到引擎。虽然在实际操作中这一步骤很简单,但是我们可以由此熟悉一下unreal中的Python API。
首先在unreal中打开之前安装的python Editor,然后新建一个PythonScript文件.
首先输入import unreal可调用unreal中的函数,然后是import os指输入输出文件。

然后定义一张我们需要导入的图片文件,最好使用绝对路径,因为相对路径的话unreal python默认加载的是引擎安装目录的位置,而不是项目的位置,所以大可不必用相对路径。注意路径的斜杠是反的。
texture = 'D:/test/python_unreal.tga'
接着我们需要创建一个函数ImportTask来定义我们的导入task。这样我们就可以在后面的程序中直接调用函数ImportTask来为我们的texture创建一个导入task。
def importTask(filename,destination_path):
task = unreal.AssetImportTask()
task.set_editor_property('automated', True)
task.set_editor_property('destination_name', '')
task.set_editor_property('destination_path', destination_path)
task.set_editor_property('filename',filename)
task.set_editor_property('replace_existing', True)
task.set_editor_property('save', True)
return task
首先以上代码中,我们给importTask两个参数,filename只要执行导入任务的文件名字,destination_path指导入进去以后的文件放在哪里。接着用unreal python的一个函数AssetImportTask来赋值task,这样就可以在后面直接调用task来给任务设置属性。对于AssetImportTask这个unreal python内部的函数
下面的set_editor_property都是在设置任务属性,比如atomated就是是否要在导入的时候发生一些已存在的覆盖等状况要不要弹出来对话框,Ture就表示avoid dialog不弹出对话框。destination_name导入进去的文件名字,后面引号为空表示默认为文件原本的名字,即导入进去不重命名;destination_path指导入进去放的位置,在调用importTask的时候可以进行设置;filename,导入之前的文件名;replace_existing,导入进去的时候要不要覆盖原有的文件;save指的是导入进去以后要不要直接保存。
属性设置完成以后将task输出以方便其他函数的调用。

Task的属性设置好了以后,我们需要一个函数来执行这个task,所以就有了接下来的执行函数executeImportTask
def executeImportTasks(tasks):
unreal.AssetToolsHelpers.get_asset_tools().import_asset_tasks(tasks)
tasks表示可以有多个任务,在调用的时候可以用中括号[,]将任务都当做列表括起来,这样在调用的时候就可以挨个调用。
大致就是使用了AssetToolsHelpers这个类下面的函数get_asset_tools,就得到了unreal里面的asset工具AssetTools,

然后再用asset工具调用了里面的函数import_asset_tasks.
按照import_asset_tasks的说明,需要把一个tasks列表传入进来,所以如果有多个导入任务的话就可以一起导入。

最后,我们需要有一个函数来同时调用importTask和executeImportTasks函数,定义函数importMyAssets,然后把importTask的返回值给texture_task,作为executeImportTasks的输入参数。
def importMyAssets():
texture_task = ImportTask(texture, '/Game/Textures')
executeImportTasks([texture_task])
导入进去以后的路径/Game/Textures表示将导入进来的图片放在Content文件夹下面新创建的textures文件夹下。
最后调用函数importMyAssets()
完整代码如下:

然后点击运行,就可以在我们的内容浏览器上面看到多出的叫做Textures的文件夹以及里面的贴图文件python_unreal.tga

后续我们还可以按照这种格式导入批量的mesh或者其他音频文件等。
- End -