Hello everyone! I try create UObject class which will self destroyed in a period of time.
Here code which I made:
.h
#pragma once
#include "TestObject.h"
#include "TO_1.generated.h"
UCLASS()
class TESTCODE_API UTO_1 : public UTestObject
{
GENERATED_BODY()
virtual void DoThing(FVector SpawnLocation, FRotator SpawnRotation, AActor* Owner, APawn* Iniciator, TSubclassOf<class ATestCodeProjectile> ProjectileClass) override;
private:
FTimerHandle TimerToDestroy;
void DestroyFunction();
};
.cpp
#include "TestCode.h"
#include "Engine.h"
#include "TestCodeProjectile.h"
#include "TO_1.h"
void UTO_1::DoThing(FVector SpawnLocation, FRotator SpawnRotation, AActor* Owner, APawn* Iniciator, TSubclassOf<class ATestCodeProjectile> ProjectileClass)
{
World = Owner->GetWorld();
if (World != NULL)
{
FActorSpawnParameters SpawnParams;
SpawnParams.Owner = Owner;
SpawnParams.Instigator = Iniciator;
World->SpawnActor<ATestCodeProjectile>(ProjectileClass, SpawnLocation, SpawnRotation, SpawnParams);
GEngine->AddOnScreenDebugMessage(-1, 2.f, FColor::Red, FString::Printf(TEXT("Projectail Spawned (from TO_1)")));
World->GetTimerManager().SetTimer(TimerToDestroy, this, &UTO_1::DestroyFunction, 3.f, false, 3.f);
}
}
void UTO_1::DestroyFunction()
{
GEngine->AddOnScreenDebugMessage(-1, 2.f, FColor::Green, FString::Printf(TEXT("Destroy Object (from TO_1)")));
}
This is all working. When I created this object and call function “DoThing” it spawned projectile and run timer which will fire “DestroyFunction” in 3 sec. As I say, it is all working perfectly. But when I try destroy object itself through “DestroyFunction” like this
void UTO_1::DestroyFunction()
{
GEngine->AddOnScreenDebugMessage(-1, 2.f, FColor::Green, FString::Printf(TEXT("Destroy Object (from TO_1)")));
this->ConditionalBeginDestroy();
this->FinishDestroy();
}
it crashes. So, why it so, and how actually I can selfdestroy UObject?