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

Unreal Engine 5使用SetupAttachment函数后崩溃如何修复?

问题原因

这是你代码编写的失误,不是UE引擎本身的Bug,崩溃原因是空指针访问:
你只在头文件中声明了各个组件的类指针,但没有在构造函数中实例化这些组件,Hull和SpringArm都是空指针,直接调用SpringArm->SetupAttachment、给RootComponent赋值空指针都会触发内存访问违例,直接导致引擎崩溃。


修复步骤

  • 第一步:在构造函数中先调用CreateDefaultSubobject实例化所有声明的组件,每个组件的命名需要唯一
  • 第二步:实例化完成后再设置RootComponent、执行组件附着逻辑

修复后的CPP文件完整代码如下:

// Fill out your copyright notice in the Description page of Project Settings.


#include "TankController.h"

#include "GameFramework/SpringArmComponent.h"
#include "Camera/CameraComponent.h"
#include "Components/StaticMeshComponent.h"

// Sets default values
ATankController::ATankController()
{
    // Set this pawn to call Tick() every frame.  You can turn this off to improve performance if you don't need it.
    PrimaryActorTick.bCanEverTick = false;

    // 第一步:先实例化所有组件
    Hull = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("Hull"));
    Wheel1 = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("Wheel1"));
    Wheel2 = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("Wheel2"));
    Turret = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("Turret"));
    Barrel = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("Barrel"));
    RecoilSystem = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("RecoilSystem"));
    SpringArm = CreateDefaultSubobject<USpringArmComponent>(TEXT("SpringArm"));
    Camera = CreateDefaultSubobject<UCameraComponent>(TEXT("Camera"));

    // 第二步:设置根组件、执行附着
    RootComponent = Hull;

    SpringArm->SetupAttachment(Hull);
    Camera->SetupAttachment(SpringArm);
    
    // 后续其他组件的附着也可以按这个逻辑添加,示例:
    // Wheel1->SetupAttachment(Hull);
    // Turret->SetupAttachment(Hull);
    // Barrel->SetupAttachment(Turret);
}

// Called when the game starts or when spawned
void ATankController::BeginPlay()
{
    Super::BeginPlay();
    
}

// Called to bind functionality to input
void ATankController::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)
{
    Super::SetupPlayerInputComponent(PlayerInputComponent);

}

注意:后续你给其他组件做附着时,也要保证先完成组件实例化,再调用SetupAttachment方法,否则仍然会出现空指针崩溃。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 07:45:03