我用c++写了一个碰撞,但是一启动就崩溃了。这是代码
.h
UCLASS()
class DIABLOCPP_API AHIT1 : public APawn
{
GENERATED_BODY()
public:
// Sets default values for this pawn's properties
AHIT1();
protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Components")
class USphereComponent* SphereComp;
UFUNCTION()
void OnActorOverlap(class UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, class UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult);
public:
// Called every frame
virtual void Tick(float DeltaTime) override;
// Called to bind functionality to input
virtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override;
};
.cpp
// Sets default values
AHIT1::AHIT1()
{
// Set this pawn to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
SphereComp = CreateDefaultSubobject<USphereComponent>("CollisionSphere");
SphereComp->SetSphereRadius(100.0f);
SphereComp->SetCollisionProfileName(TEXT("Projectile"));
RootComponent = SphereComp;
}
// Called when the game starts or when spawned
void AHIT1::BeginPlay()
{
Super::BeginPlay();
SphereComp->OnComponentBeginOverlap.AddDynamic(this, &AHIT1::OnActorOverlap);
}
// Called every frame
void AHIT1::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
}
// Called to bind functionality to input
void AHIT1::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)
{
Super::SetupPlayerInputComponent(PlayerInputComponent);
}
void AHIT1::OnActorOverlap(UPrimitiveComponent* HitComp, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult)
{
GEngine->AddOnScreenDebugMessage(-1, 15.0f, FColor::Yellow, TEXT("Some debug message!"));
}
呼叫线路时崩溃:
SphereComp->OnComponentBeginOverlap.AddDynamic(this, &AHIT1::OnActorOverlap);
我试图在构造函数中绑定碰撞,但即使没有崩溃,它也不起作用。我不明白我的错误,在其他更复杂的例子中一切正常。
CreateDefaultSubobject
类型转换应该有 TEXT
类型 arg.
变化:
SphereComp = CreateDefaultSubobject<USphereComponent>("CollisionSphere");
对此:
SphereComp = CreateDefaultSubobject<USphereComponent>(TEXT("CollisionSphere"));
之后,您的 SphereComp 将被创建,并且不会是 nullptr(我希望如此呵呵)
确保使用
SetRootComponent()
方法调用而不是直接分配 RootComponent
变量。 SetRootComponent()
在幕后做了一些额外的工作,将其设置为 actor 的实际根组件,并为您分配 RootComponent
变量。
现在换个说法,即使有我提到的上述可能的修复方法,我也遇到过这些
nullptr
情况在极少数情况下发生,但是在你这样干净的棋子上?这太奇怪了。这通常是与演员已经存在的组件的命名冲突。
在这些情况下,我所做的是,将变量名称以及
CreateDefaultSubobject
中的名称字符串重命名为其他名称,例如“Sphere Component”或称其为“chocolate”或其他名称,只是为了与众不同。确保你也使用了TEXT()
宏。
最重要的是,就像完整性检查一样。我从项目中删除了
Binaries/
、Intermediate/
和 Saved/
目录以及 .sln
文件。然后我右键单击.uproject
文件和"Generate Visual studio project files"
并再次重建整个游戏。
希望这有帮助!
我解决了这个问题。当我在 BeginPlay 中添加这一行时问题就解决了
SphereComp->SetCollisionProfileName(TEXT("Projectile"));