[SOLVED] Spawned UStaticMeshComponent gets automatically deleted after some time

Hello everyone,

I created an HUD button, when the button is clicked a C++ method is called to spawn a static mesh in the world, I have the path of the static mesh.

Here’s my simplified code (I removed all the null pointer tests, It’s a code I found online and I adapted)


UStaticMesh* myMesh = Cast<UStaticMesh>(StaticLoadObject(UStaticMesh::StaticClass(), NULL, *pathStaticMesh));
currentSpawnMesh = NewObject<UStaticMeshComponent>(UStaticMeshComponent::StaticClass());
currentSpawnMesh->SetStaticMesh(myMesh);
currentSpawnMesh->SetWorldLocation(FVector(0, 0, 0));
currentSpawnMesh->RegisterComponentWithWorld(GetWorld());

The problem : after around 20 or 30 seconds the UStaticMeshComponent gets automatically deleted, and my code isn’t doing anything else in particular, I’m not deleting currentSpawnMesh later in the code

How can I prevent the UStaticMeshComponent to get automatically deleted? Is it a bug or a mistake by me?

Thanks in advance.

currentSpawnMesh needs to be a UPROPERTY, otherwise garbage collection will destroy it.

Thank you very much, I indeed forgot the UPROPERTY, it works now.