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

Unreal C++调用AIController的MoveToLocation触发崩溃问题求助

崩溃根因

你的空指针异常来自于AIController变量初始化时机错误:
你在ASpiderCharacter的构造函数中调用GetController()获取AIController,但Unreal中角色构造完成后,才会由引擎分配绑定对应的AIController,构造阶段GetController()返回值为nullptr,后续重叠事件中直接调用AIController->WalkAway就触发了空指针访问崩溃。


修复步骤

  1. 移除构造函数中的AIController赋值逻辑,改为在角色的BeginPlay中获取:
    首先在SpiderCharacter.h中添加BeginPlay声明:
protected:
    virtual void BeginPlay() override;

然后在SpiderCharacter.cpp中实现:

void ASpiderCharacter::BeginPlay()
{
    Super::BeginPlay();
    AIController = Cast<ASpiderAIController>(GetController());
}
  1. 在调用WalkAway前添加空指针校验,同时建议对玩家控制器、玩家pawn也添加校验,避免极端情况崩溃,另外你原逻辑中固定X/Y各减500不是正确的远离玩家方向,可替换为如下实现:
    修改OnOverlapBegin逻辑:
void ASpiderCharacter::OnOverlapBegin(class UPrimitiveComponent* OverlappedComp, class AActor* OtherActor, class UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult)
{
    if (OtherActor && (OtherActor != this) && OtherComp && AIController) 
    {
        APlayerController* PlayerController = GetWorld()->GetFirstPlayerController();
        if (!PlayerController || !PlayerController->GetPawn())
        {
            return;
        }
        // 获取玩家位置
        FVector PlayerPosition = PlayerController->GetPawn()->GetActorLocation();
        // 计算远离玩家的方向
        FVector EscapeDir = GetActorLocation() - PlayerPosition;
        EscapeDir.Z = 0; // 忽略高度差,仅水平面移动
        EscapeDir.Normalize();
        FVector NewLocation = GetActorLocation() + EscapeDir * 500.f;
        float AcceptanceRadius = 100.f;

        AIController->WalkAway(NewLocation, AcceptanceRadius);
        UE_LOG(LogTemp,Warning,TEXT("重叠触发,目标Actor:%s"),  *OtherActor->GetName());
    }
}
  1. 额外确认项:在NPC角色的属性面板中,将Auto Possess AI选项设置为Placed in World or Spawned,保证NPC生成时自动绑定SpiderAIController。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 08:15:05