How to prevent projectile object from being garbage collected.

Hi, i’m new to Unreal and trying to figure out why my projectile is being garbage collected.

I allocate it in the constructor of my character using

ProjectileClass = CreateDefaultSubobject<AProjectile>(L"Projectile");

The Character object I am using it in still exists and is valid. Eventually after a random period of time just the projectile becomes invalid and gets sent through the garbage collector. I can find that it was invalid and solve it by using

if (!ProjectileClass->IsValidLowLevel())
{
	ProjectileClass = NewObject<AProjectile>();
}

Which solves all the crashes. But I am curious how to prevent it from being garbage collected when it’s being used in the first place.

It needs to be in a UPROPERTY in the header file to not be garbage collected.

UPROPERTY()
  UObject* YourObject;

garbage-collection-dynamic-memory-allocation

garbage_collection_of_variables

garbage-collection-in-unreal-engine

Is it declared a UPROPERTY ?

AProjectile is an actor class, use SpawnActor instead of NewObject.

You are right. That also makes my comment about the UPROPERTY invalid in this case, because the level automatically references spawned actors.
Also, isn’t “CreateDefaultSubobject” only valid for ActorComponents?

Well kind of. AActors and UActorComponents are both UObjects, and garbage collection happens at the UObject level. CreateDefaultSubobject is a function of UObject and can be used with any UObject (not just components). I believe it establishes a subobject relationship in the constructor (that works with the CDO system). So if you have a UObject-derived UPROPERTY in a class you can call CreateDefaultSubobject in the constructor to populate it (in the CDO). I’m not entirely clear what the difference is between CreateDefaultSubobject and using NewObject in the constructor. I also could be wrong about everything I just said.