You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

UE5.1 Python脚本:提取Unreal Vector坐标及获取指定Actor位置

问题描述

在Unreal Engine 5.1中使用Python脚本时遇到两个问题:

  1. 尝试提取Unreal Vector的x、y、z分量,使用vector[0]、vector(0)、vector{0}等语法均无效,报错提示Vector对象不可迭代、不可调用、不可下标访问。
  2. 尝试获取名为cart和cylinder_bp的Actor位置,使用Assets = unreal.Actor(name='cylinder_bp').get_actor_location()写法无效。

测试脚本:

import unreal
import torch

Assets = unreal.Actor(name='cylinder_bp').get_actor_location()

print(Assets)
#print(torch.tensor(Assets))

报错信息:

LogPython: Error: Traceback (most recent call last):
LogPython: Error:   File "C:/Devanshu/RL/actors.py", line 6, in <module>
LogPython: Error:     for a in Assets:
LogPython: Error: TypeError: 'Vector' object is not iterable
LogPython: C:\Devanshu\RL\actors.py
LogPython: <Struct 'Vector' (0x000001C98DB7F9C0) {x: 0.000000, y: 0.000000, z: 0.000000}>
LogPython: C:\Devanshu\RL\actors.py
LogPython: Error: Traceback (most recent call last):
LogPython: Error:   File "C:/Devanshu/RL/actors.py", line 6, in <module>
LogPython: Error:     print(Assets(0))
LogPython: Error: TypeError: 'Vector' object is not callable
LogPython: C:\Devanshu\RL\actors.py
LogPython: Error: Traceback (most recent call last):
LogPython: Error:   File "C:/Devanshu/RL/actors.py", line 6, in <module>
LogPython: Error:     print(Assets[0])
LogPython: Error: TypeError: 'Vector' object is not subscriptable

解决方法

1. 正确获取指定名称的Actor位置

不能直接通过unreal.Actor(name='xxx')实例化Actor,这只会创建空的Actor对象,而非场景中已存在的实例。需通过UE编辑器API获取场景内的Actor:

方法一:按名称直接查找

import unreal

# 获取指定名称的Actor
target_actor = unreal.EditorLevelLibrary.get_actor_by_name("cylinder_bp")
if target_actor:
    # 获取Actor位置(返回Vector结构体)
    actor_location = target_actor.get_actor_location()
    print(actor_location)
else:
    print("未找到名为cylinder_bp的Actor")

方法二:遍历筛选同名Actor

如果场景中有多个同名Actor,可遍历所有Actor筛选:

import unreal

# 获取场景中所有Actor
all_actors = unreal.EditorLevelLibrary.get_all_level_actors()
# 筛选名称匹配的Actor
target_actors = [actor for actor in all_actors if actor.get_name() == "cylinder_bp"]

for actor in target_actors:
    location = actor.get_actor_location()
    print(f"Actor {actor.get_name()} 的位置:{location}")

2. 提取Unreal Vector的x/y/z分量

Unreal的Vector在Python中是结构体类型,不能通过索引或调用方式访问分量,需直接访问其属性:

# 假设已获取到Vector对象(比如上面的actor_location)
vector = actor_location

# 直接访问x、y、z属性
x = vector.x
y = vector.y
z = vector.z

print(f"X分量:{x}, Y分量:{y}, Z分量:{z}")

# 转换为PyTorch张量时,需手动传入分量值
import torch
tensor = torch.tensor([x, y, z])
print(tensor)

注意事项

  • 确保脚本运行时,目标Actor已存在于当前打开的关卡中。
  • UE Python API的EditorLevelLibrary仅在编辑器模式下可用,打包后的游戏中无法使用。

内容的提问来源于stack exchange,提问作者Devanshu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 14:02:48