UE4中如何引用玩家Pawn上的Box碰撞体绑定BeginOverlap动态函数
UE4 Box碰撞体Overlap事件绑定解决方案
场景1:已在C++头文件声明碰撞体成员变量
如果你在ARasenmaeher类的头文件中已经声明了对应UBoxComponent成员,示例头文件代码如下:
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Collision", meta = (AllowPrivateAccess = "true")) UBoxComponent* CollisionBox;
那么问号处直接填写碰撞体的成员变量名即可,注意删除原代码中多余的括号,修改后完整代码:
void ARasenmaeher::BeginPlay() { CollisionBox->OnComponentBeginOverlap.AddDynamic(this, &ARasenmaeher::OnBeginOverlap); }
场景2:未在C++头文件声明碰撞体成员
如果碰撞体是在蓝图中添加,或者你不想单独声明成员变量,可以通过FindComponentByClass动态查找碰撞体后绑定,完整代码如下:
void ARasenmaeher::BeginPlay() { Super::BeginPlay(); UBoxComponent* BoxComp = FindComponentByClass<UBoxComponent>(); // 非空判断避免空指针崩溃 if (BoxComp) { BoxComp->OnComponentBeginOverlap.AddDynamic(this, &ARasenmaeher::OnBeginOverlap); } }
注意事项
- 如果当前Pawn存在多个Box碰撞体,不要使用
FindComponentByClass查找,优先选择头文件声明成员的方式,或者给目标碰撞体设置唯一Tag后通过FindComponentByTag查找,避免绑错组件 - 回调函数
OnBeginOverlap需要在头文件中用UFUNCTION()标记,且函数签名必须符合委托要求,标准签名如下:
UFUNCTION() void OnBeginOverlap(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult);
内容的提问来源于stack exchange,提问作者Whovian1701
相关产品推荐
相关产品推荐

