UE Python笔记

插件

官方

商城

Python Editorhttps://www.fab.com/listings/f4c99ba0-1a86-4f6a-b19d-2fd13f15961b

GitHUB

好像只更新到了2020年4.2x的版本。可能有大佬改了5.x的版本。也希望分享给我一份。谢谢

https://github.com/20tab/UnrealEnginePython

学习笔记

网上教程一大堆。边学边写。学会到哪写到哪。哪天不更新了。就是这个笔记又太监了。写的不对的地方喷的时候也麻烦轻点。

Sequencer中的Python脚本https://dev.epicgames.com/documentation/zh-cn/unreal-engine/python-scripting-in-sequencer-in-unreal-engine?application_version=5.0

UE 使用Python控制Sequencehttps://zhuanlan.zhihu.com/p/13347612063

这下面这个文档解释的比较细:

UE5 中用 Python 接口创建 Level Sequence 与设置 TriggerEvent-腾讯云开发者社区-腾讯云遇到了一个美术需求,需要批量读取一段动画,制作成 UE 中的 Level Sequence,然后给动画添加几个 Event Track。随后,需要在 Event Track 中添加 Trigger Event,设置插件 uDraper 布料的缓存数据路径。总之,最终效果如下:https://cloud.tencent.com/developer/article/2146577

跟着学的案例
目前还没“复刻”成功=复制粘贴都不行.gif:

复刻成功=没学会:

1.这个Json文件少了个]。其他按照他这个做基本能复刻。

UE5 Python脚本自动化Sequence Key帧_ue sequnece python-CSDN博客

2.Json(latitude,longitude,elevation)= Python(uex,uey,uez)。因为我没有PythonEditor所以改成了固定的main方式。

【UE4】Python读取Json数据创建对应关卡序列_json设计关卡-CSDN博客

Json相关

读取(祖传代码)

(filename = 外部输入的名字)特别要注意的是Json格式问题

 #def JsonGetData(filename):
    # 读取/项目目录/JsonFile中的JSON文件数据存入json_data
    root_path = unreal.SystemLibrary.get_project_directory() + 'Content/Json/'
    final_path = root_path + filename + '.json'
    fp = open(final_path, 'r', encoding='utf-8')
    json_str = fp.read()
    json_data = json.loads(json_str)
    unreal.log("=== INFO: Json Get OK ===")
    return json_data
 

报这个错误就是Json格式出现问题了。

JSON在线 | JSON解析格式化—SO JSON在线工具

解析

示例 
"commands": [
   {
     "commandtype": "Create",
     "objectcreateinfo": {
       "object": {
         "id": "1",
         "objecttype": "myship"
       },
       "propertys": [
         {
           "key": "DisplayName",
           "value": "我的船",
           "propertytype": "String",
           "displaystring": "我的船"
         }
       ],
 #读取各项数据创建关键帧
 commands = json_data["commands"]

#循环获取commands里面的数据
 for index in range(0,len(commands)):
 #for command in commands:

     #json中commandtype为Create时执行
     if commands[index]["commandtype"] == "Create":
          
         # 获取到"commands->objectcreateinfo->object->objecttype"这一层是否等于myship
         if commands[index]["objectcreateinfo"]["object"]["objecttype"] == "myship":

Main方法

没有这个函数的话。直接右键运行是不会执行任何东西的。

//有这个右键脚本运行才能有效
if __name__ == '__main__':
    create()

python获取场景中的actor
  # 获取Actor子系统以抓取选定的Actor
  actor_system = unreal.get_editor_subsystem(unreal.EditorActorSubsystem)
  # 获取选定的Actor
  actor = actor_system.get_selected_level_actors()[0]
 
  # 将Actor作为可拥有物添加到关卡中
  actor_binding = level_sequence.add_possessable(actor)
 
  
  # 刷新以直观地查看添加的新绑定
  unreal.LevelSequenceEditorBlueprintLibrary.refresh_current_level_sequence()

# 使用绑定将轨迹添加到Sequencer(由轨迹类型指定)
  transform_track = actor_binding.add_track(unreal.MovieScene3DTransformTrack) 
属性/状态
    #transform
    # 将分段添加到轨迹以便能够设置范围、参数或属性
    transform_section = transform_track.add_section()
  
    #位移:
    获取位置的xyz通道
    channel_location_x = transform_section.get_channels()[0]
    channel_location_y = transform_section.get_channels()[1]
    channel_location_z = transform_section.get_channels()[2]

    #获取旋转yz的关键帧
    channel_rotation_x = transform_section.get_channels()[3]
    channel_rotation_y = transform_section.get_channels()[4]
    channel_rotation_z = transform_section.get_channels()[5]

     #添加关键帧
     links = json_path["links"]
     for index in range(0, len(links)):
     new_time0 = unreal.FrameNumber(value=index*int(json_path["fov"]))
     #channel_fov.add_key(new_time0, float(json_path["fov"]), 0.0)
     channel_location_x.add_key(new_time0, float(links[index]["x"]), 0.0)
     channel_location_y.add_key(new_time0, float(links[index]["y"]), 0.0)
     channel_location_z.add_key(new_time0, float(links[index]["z"]), 0.0)
     channel_rotation_x.add_key(new_time1, float(links[index]["roll"]), 0.0)
     channel_rotation_y.add_key(new_time1, float(links[index]["pitch"]), 0.0)
     channel_rotation_z.add_key(new_time1, float(links[index]["yaw"]), 0.0)
        
    
      #设置显示隐藏:
      #为actor添加可视性(隐藏)关键帧
      channel_visibility_bool = visibility_section.get_channels()[0]

      #添加关键帧
      channel_visibility_bool.add_key(new_time,False)
获取蓝图自定义的变量(感谢DeepSeeK)
import unreal

# 方法1:获取当前关卡中所有蓝图实例
def get_blueprint_variable(actor_class_name, variable_name):
    # 获取当前关卡所有Actor
    actors = unreal.EditorLevelLibrary.get_all_level_actors()
    
    # 遍历查找目标蓝图类实例
    for actor in actors:
        if actor.get_class().get_name() == actor_class_name:
            # 检查变量是否存在
            if actor.property_exists(variable_name):
                value = actor.get_editor_property(variable_name)
                print(f"Found variable '{variable_name}': {value}")
                return value
            else:
                print(f"Variable '{variable_name}' not found in actor.")
                return None
    print(f"Actor of class '{actor_class_name}' not found.")
    return None

# 使用示例:获取类名为"MyBlueprintClass"的Actor的"MyVariable"变量
get_blueprint_variable("MyBlueprintClass", "MyVariable")

# 方法2:通过选中Actor获取(需提前在编辑器中选中)
selected_actors = unreal.EditorLevelLibrary.get_selected_level_actors()
if selected_actors:
    actor = selected_actors[0]
    value = actor.get_editor_property("MyVariable")
    print(f"Selected actor's variable value: {value}")

#我自己是用的这个写法(上面都是DeepSeek发的)
 # 获取Actor子系统以抓取选定的Actor
 actor_system = unreal.get_editor_subsystem(unreal.EditorActorSubsystem)
 # 获取选定的Actor
 actor = actor_system.get_selected_level_actors()[0]
 print(actor)
 value = actor.get_editor_property("TestInt")
Sequence添加Int/float轨道
 #  创建整型轨道(int)
 int_track = actor_binding.add_track(unreal.MovieSceneIntegerTrack)
 property_name_int = "VAR_Index"
 int_track.set_property_name_and_path(property_name_int, property_name_int)

  #将分段添加到轨迹以便能够设置范围、参数或属性
 int_section = int_track.add_section()
   #设置开始和结束帧数
 int_section.set_start_frame_seconds(0)
 int_section.set_end_frame_seconds(600)
 channel_int = int_section.get_channels()[0]  # 假设第一个通道是整型通道     

  #  创建浮点轨道(假设变量类型为float)
 float_track = actor_binding.add_track(unreal.MovieSceneFloatTrack)
 property_name = "Alpha"
 float_track.set_property_name_and_path(property_name, property_name)

 #将分段添加到轨迹以便能够设置范围、参数或属性
 float_section = float_track.add_section()
   #设置开始和结束帧数
 float_section.set_start_frame_seconds(0)
 float_section.set_end_frame_seconds(600)
 channel_float = float_section.get_channels()[0]  # 假设第一个通道是float通道

 links = json_path["links"]
 for index in range(0, len(links)):
     new_time0 = unreal.FrameNumber(value=index*int(json_path["fov"]))
     #channel_fov.add_key(new_time0, float(json_path["fov"]), 0.0)
     channel_int.add_key(new_time0, float(links[index]["va"]), 0.0)
     #print("index",float(links[index]["va"]))
     #float_track.add_key(new_time0, float(links[index]["al"]), 0.0)
     channel_float.add_key(new_time0, float(links[index]["al"]), 0.0)

尝试
Json
{
  "starttimestamp": 0,
  "endtimestamp": 600,
  "frametime": 60,
  "seqname": "VideoPlayerSeqSpline",
  "fov": 60,
  "links": [
    {
      "x": 0,
      "y": 0,
      "z": 0
    },
    {
      "x": 1088.2844551244866,
      "y": -6.1749946553391055e-05,
      "z": 9.0949470177292824e-13
    },
    {
      "x": 962.03462911456836,
      "y": 1326.0205919409059,
      "z": -2.1247876702545909e-07
    },
    {
      "x": 1655.6119959682651,
      "y": 1939.9672775097956,
      "z": 6.2318827929175313e-06
    },
    {
      "x": 2921.7209372361831,
      "y": 1163.8111134544288,
      "z": -1.546140993013978e-11
    },
    {
      "x": 3168.7212710348158,
      "y": -502.86935341987612,
      "z": 36.471531137039221
    },
    {
      "x": 3168.7212776581878,
      "y": -1900.5658369533642,
      "z": 36.471531137031945
    },
    {
      "x": 3168.7212858682856,
      "y": -2762.9053314381854,
      "z": 15.992892525690252
    },
    {
      "x": 1705.8193762352209,
      "y": -2821.7894823782708,
      "z": 15.992892525679338
    },
    {
      "x": 1705.8193759169985,
      "y": -1617.7851900597982,
      "z": 15.992892525679792
    },
    {
      "x": 273.03898678036694,
      "y": -1617.7851516590028,
      "z": 15.992892525679792
    }
  ]
}
Python
#连接虚幻API库
import unreal,json,os
 
def JsonGetData(filename):
    # 读取/项目目录/JsonFile中的JSON文件数据存入json_data
    root_path = unreal.SystemLibrary.get_project_directory() + 'Content/Json/'
    final_path = root_path + filename + '.json'
    fp = open(final_path, 'r', encoding='utf-8')
    json_str = fp.read()
    json_data = json.loads(json_str)
    unreal.log("=== INFO: Json Get OK ===")
    return json_data
 
def Seqcreate():
    json_path = JsonGetData("test")
 
    # 获取资产工具
    asset_tools = unreal.AssetToolsHelpers.get_asset_tools()
 
    # 在根内容文件夹中创建一个名为LevelSequenceName的关卡序列
    level_sequence = unreal.AssetTools.create_asset(asset_tools, asset_name=json_path["seqname"],
                                                    package_path="/Game/Sequence/",
                                                    asset_class=unreal.LevelSequence,
                                                    factory=unreal.LevelSequenceFactoryNew())
    # 创建一个帧率对象并设置为所需的fps数值
    frame_rate = unreal.FrameRate(numerator=json_path["frametime"], denominator=1)
    # 设置显示速率
    level_sequence.set_display_rate(frame_rate)

    # 设置播放范围
    level_sequence.set_playback_start(json_path["starttimestamp"])
    level_sequence.set_playback_end(json_path["endtimestamp"])
 
    # 获取Actor子系统以抓取选定的Actor
    actor_system = unreal.get_editor_subsystem(unreal.EditorActorSubsystem)
    # 获取选定的Actor
    actor = actor_system.get_selected_level_actors()[0]
   
    # 将Actor作为可拥有物添加到关卡中
    actor_binding = level_sequence.add_possessable(actor)
   
    
    # 刷新以直观地查看添加的新绑定
    unreal.LevelSequenceEditorBlueprintLibrary.refresh_current_level_sequence()

  # 使用绑定将轨迹添加到Sequencer(由轨迹类型指定)
    transform_track = actor_binding.add_track(unreal.MovieScene3DTransformTrack) 

    # 将分段添加到轨迹以便能够设置范围、参数或属性
    transform_section = transform_track.add_section()
  
    transform_section.set_start_frame_seconds(json_path["starttimestamp"])
    transform_section.set_end_frame_seconds(json_path["endtimestamp"])

    channel_location_x = transform_section.get_channels()[0]
    channel_location_y = transform_section.get_channels()[1]
    channel_location_z = transform_section.get_channels()[2]
   

    links = json_path["links"]
    for index in range(0, len(links)):
        new_time0 = unreal.FrameNumber(value=index*int(json_path["fov"]))
        #channel_fov.add_key(new_time0, float(json_path["fov"]), 0.0)
        channel_location_x.add_key(new_time0, float(links[index]["x"]), 0.0)
        channel_location_y.add_key(new_time0, float(links[index]["y"]), 0.0)
        channel_location_z.add_key(new_time0, float(links[index]["z"]), 0.0)

         
    unreal.EditorAssetLibrary.save_loaded_asset(level_sequence, False)
    # 刷新以直观地查看新增的轨迹和分段
    unreal.LevelSequenceEditorBlueprintLibrary.refresh_current_level_sequence()
 
    unreal.log("=== INFO: Seq Create Completed Please check the file===")

if __name__ == '__main__':
    Seqcreate()

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:/a/978542.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

SQL_优化

1 SQL优化 (1) 数据读取 ①分区裁剪:使用时只读取需要的分区. ②列裁剪:读取操作(select、where、join、group by、sort by等),不读取不需要的列,减少IO消耗. (2) 数据筛选 ①分区先过滤,区分度大的字段先过滤. ②不在筛选字段上使用函数和表达式. (3) 分组聚合 ①使用窗口函数…

centos9之ESXi环境下安装

一、centos9简介 CentOS Stream 9是一个基于RHEL(Red Hat Enterprise Linux)的开源操作系统。它是CentOS Stream系列的最新版本。CentOS Stream是一个中间发行版,位于RHEL和Fedora之间,旨在提供更及时的软件更新和新功能。CentOS …

Vue2+Element实现Excel文件上传下载预览【超详细图解】

目录 一、需求背景 二、落地实现 1.文件上传 图片示例 HTML代码 业务代码 2.文件下载 图片示例 方式一:代码 方式二:代码 3.文件预览 图片示例 方式一:代码 方式二:代码 一、需求背景 在一个愉快的年后&#xff…

在线会议时, 笔记本电脑的麦克风收音效果差是为什么

背景 最近在线面试. 使用腾讯会议或者飞书, 戴耳机参加在线面试, 遇到好几个面试官说我的音质不好. 一直没在意, 后来反思, 应该是电脑哪里出了问题. 排查 先买了一副品牌有线耳机, 测试后本地录制的声音仍然品质很差去掉耳机延长线后, 麦克风品质仍然很差最终找到答案, 原…

【十二】Golang 映射

💢欢迎来到张胤尘的开源技术站 💥开源如江河,汇聚众志成。代码似星辰,照亮行征程。开源精神长,传承永不忘。携手共前行,未来更辉煌💥 文章目录 映射映射的定义映射初始化make 函数使用字面量 源…

【HarmonyOS Next】鸿蒙TaskPool和Worker详解 (一)

【HarmonyOS Next】鸿蒙TaskPool和Worker详解 (一) 一、TaskPool和Worker如何实现多线程?各自特点是什么? 在鸿蒙中通过TaskPool和Worker实现多线程并发,两者都基于Actor并发模型实现。 Actor并发模型,每…

FFmpeg.NET:.NET 平台上的音视频处理利器

FFmpeg.NET 是一个封装了 FFmpeg 功能的 .NET 库,能够方便地在 C# 项目中处理音视频文件。它支持多种操作,包括转码、剪辑、合并、分离音频等。 功能 解析元数据从视频生成缩略图使用以下参数将音频和视频转码为其他格式: 码率(…

计算机网络————(一)HTTP讲解

基础内容分类 从TCP/IP协议栈为依托,由上至下、从应用层到基础设施介绍协议。 1.应用层: HTTP/1.1 Websocket HTTP/2.0 2.应用层的安全基础设施 LTS/SSL 3.传输层 TCP 4.网络层及数据链路层 IP层和以太网 HTTP协议 网络页面形成基本 流程&#xff1a…

源码压缩包泄露

##解题思路 因为网站的文件都放在www下面,所以直接访问/www.zip就可以得到网页的源码压缩包 在fl000g.txt这个文件中看到一个flag{flag_here}不像是真的flag,尝试提交ctfshow{flag_here},果然提交失败 打开文件属性之类的,也没有…

组态软件在物联网中的应用

随着物联网的快速发展,组态软件在物联网中的应用也越来越广泛。组态软件是一种用于创建和管理物联网系统的可视化工具,它能够将传感器、设备和网络连接起来,实现数据的采集、分析和可视化。本文将探讨组态软件在物联网中的应用,并…

Java+SpringBoot+Vue+数据可视化的音乐推荐与可视化平台(程序+论文+讲解+安装+调试+售后)

感兴趣的可以先收藏起来,还有大家在毕设选题,项目以及论文编写等相关问题都可以给我留言咨询,我会一一回复,希望帮助更多的人。 系统介绍 在互联网技术以日新月异之势迅猛发展的浪潮下,5G 通信技术的普及、云计算能力…

(论文)PartialSpoof 数据库和检测话语中嵌入的短假语音片段的对策

The PartialSpoof Database and Countermeasures for the Detection of Short Fake Speech Segments Embedded in an Utterance 摘要 自动说话人验证容易受到各种作和欺骗,例如文本到语音合成、语音转换、重放、篡改、对抗性攻击等。我们考虑一种称为“部分欺骗”…

Leaflet介绍及使用示例

一、Leaflet介绍 Leaflet是一个开源的JavaScript库,专门用于构建交互式的地图应用程序。它以其轻量级、高性能和易于使用的API而著称,方便开发者在网页中集成地图功能。Leaflet支持多种地图提供商的瓦片图层,如OpenStreetMap、Mapbox等&…

【笔记】redis回忆录(未完 重头过一遍)

了解 redis在linux上运行 没有window版本 有也是微软自己搞的 (一)安装与修改配置 1.在linux虚拟机上 安装gcc依赖 然后再usr/local/src解压在官网下载好的redis安装包 直接拖进去 tar -zxvf 安装包名字 tab键补齐 解压成功 进入软件 并执行编译命令…

使用 Apache Dubbo 释放 DeepSeek R1 的全部潜力

作者:陈子康,Apache Dubbo Contributor 2025年1月20日,国产大模型公司深度求索(DeepSeek)正式发布了大语言模型 DeepSeek-R1,并同步开源其模型权重。通过大规模强化学习技术,DeepSeek-R1 显著提…

Unity TMPro显示中文字体

TMP默认的字体只能显示英语,那么怎么显示中文呢 1、找到支持中文的字体文件 在c盘搜索Fonts文件夹有很多支持中文的字体文件 我这里选择雅黑 PS.双击打开发现里面有粗体细体普通三个版本,也可以只导入一个版本进去 2、将其拖入到unity Assets里面 3…

【MySQL篇】数据库基础

目录 1,什么是数据库? 2,主流数据库 3,MySQL介绍 1,MySQL架构 2,SQL分类 3,MySQL存储引擎 1,什么是数据库? 数据库(Database,简称DB&#xf…

Linux 日志系统·

目录 一、前言 二、实现一个简单的日志 1.可变参数 2.日志等级 3.日志时间 4.打印每一条参数 5.合并两个缓冲区 6.封装日志函数 三、完整代码 一、前言 当我们写一个函数,例如打开文件open,当我们打开失败的时候,会调用perror看到错误…

【PromptCoder】使用 package.json 生成 cursorrules

【PromptCoder】使用 package.json 生成 cursorrules 在当今快节奏的开发世界中,效率和准确性至关重要。开发者们不断寻找能够优化工作流程、帮助他们更快编写高质量代码的工具。Cursor 作为一款 AI 驱动的代码编辑器,正在彻底改变我们的编程方式。但如…

【VUE】vue-i18n: Uncaught SyntaxError: Not available in legacy mode

报错: 解决方法: 找到 createI18n 并加上 legacy: false,