FindComponentByClass()
UPhysicsHandleComponent 是 Unreal Engine 中的一个组件,用于操作物理对象。通常用于抓取、拖拽和移动物体等交互行为。
后面我们会使用 UPhysicsHandleComponent 组件抓取物体。如图 1 所示,我们在人物蓝图中,点击左上角添加按钮,搜索“physics handle”,并添加。用英文就能搜索到,显示的是中文“物理柄组件”。对应的图标也很形象,是一只手抓着一个方块。

添加好组件之后,我们需要在代码中获取到它。可以使用 FindComponentByClass() 方法。
FindComponentByClass() 是 Unreal Engine 中 AActor 类的一个方法,用于查找并返回指定类型的组件。它会在当前 AActor 的所有组件中,按类型查找第一个符合要求的组件。如果找到了符合条件的组件,就会返回该组件的指针;如果没有找到,则返回 nullptr。
如代码清单 1 所示,我们来到人物蓝图的 Grabber 场景组件中,在 BeginPlay 函数中增加组件的获取测试。
- #include "PhysicsEngine/PhysicsHandleComponent.h"
- // Called when the game starts
- void UGrabber::BeginPlay()
- {
- Super::BeginPlay();
- UPhysicsHandleComponent* PhysicsHandle = GetOwner()->FindComponentByClass<UPhysicsHandleComponent>();
- if (PhysicsHandle != NULL)
- {
- UE_LOG(LogTemp, Display, TEXT("Got Physics Handle: %s"), *PhysicsHandle->GetName());
- }
- }
运行程序,可以在控制台中看到预期的打印:
- LogTemp: Display: Got Physics Handle: PhysicsHandle