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

Unreal Engine中如何返回FHitResult?C++适配蓝图调用难题

解决方法

方案1:修改函数返回值为FHitResult

直接把void改成FHitResult,函数最后返回OutHit即可。注意要给函数加上UFUNCTION(BlueprintCallable)宏,确保蓝图能调用并获取返回值。

头文件声明修改:

UFUNCTION(BlueprintCallable, Category = "Interaction")
FHitResult Interact();

cpp实现修改:

FHitResult AMeCharacter::Interact() {
    FHitResult OutHit;
    FVector Start = Camera->GetComponentLocation();

    FVector ForwardVector = Camera->GetForwardVector();
    FVector End = ((ForwardVector * 150.f) + Start);
    FCollisionQueryParams CollisionParams;

    DrawDebugLine(GetWorld(), Start, End, FColor::Red, false, 3, 0.5);
    bool bHit = GetWorld()->LineTraceSingleByChannel(OutHit, Start, End, ECC_Visibility, CollisionParams);

    if (bHit)
    {
        if (!OutHit.GetActor())
            return OutHit;
        if (OutHit.GetActor()->GetClass()->ImplementsInterface(UInteractionInterface::StaticClass())) {
            UE_LOG(LogTemp, Warning, TEXT("%s"), *OutHit.GetActor()->GetName());
            GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, TEXT("Implements Interface"));
        }
        else
            GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, TEXT("Doesn't implement interface"));
    }
    return OutHit; // 无论是否命中都返回结果
}

在蓝图中调用这个函数时,可直接获取返回的FHitResult,后续逻辑基于该结果处理即可。

方案2:使用输出参数(引用传递)

如果不想修改返回值类型,可给函数添加FHitResult&类型的输出参数,UE4蓝图会自动将其识别为输出引脚,调用后就能拿到结果。

头文件声明修改:

UFUNCTION(BlueprintCallable, Category = "Interaction")
void Interact(FHitResult& OutHitResult);

cpp实现修改:

void AMeCharacter::Interact(FHitResult& OutHitResult) {
    FVector Start = Camera->GetComponentLocation();

    FVector ForwardVector = Camera->GetForwardVector();
    FVector End = ((ForwardVector * 150.f) + Start);
    FCollisionQueryParams CollisionParams;

    DrawDebugLine(GetWorld(), Start, End, FColor::Red, false, 3, 0.5);
    bool bHit = GetWorld()->LineTraceSingleByChannel(OutHitResult, Start, End, ECC_Visibility, CollisionParams);

    if (bHit)
    {
        if (!OutHitResult.GetActor())
            return;
        if (OutHitResult.GetActor()->GetClass()->ImplementsInterface(UInteractionInterface::StaticClass())) {
            UE_LOG(LogTemp, Warning, TEXT("%s"), *OutHitResult.GetActor()->GetName());
            GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, TEXT("Implements Interface"));
        }
        else
            GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, TEXT("Doesn't implement interface"));
    }
}

在蓝图调用时,只需拖出一个Hit Result类型的变量连接到函数的输出引脚,调用完成后该变量会被自动赋值,直接用于后续逻辑即可。

两种方案都能满足需求,可根据代码结构习惯选择:方案1更直接,适合仅需返回Hit结果的场景;方案2可配合额外返回值(如bool类型的交互成功状态)使用,扩展性更强。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 14:02:08