Assigning TSubClassOf to a pointer

I am quite new to programming C++ in unreal, so I hope that my question is reasonable (though after continuous searching, I couldn’t find an answer to it). In my character class, I created a variable of type ACollectableObject* and tried to assign a blueprint derived from that class to it in the editor. I realized that I was not able to assign my blueprint, however if I instead created a variable of type TSubclassOf, I was. The problem is that I need my variable to be a pointer, not a TSubclass - is there any way that I can assign my blueprint and then convert it to a pointer? Any advice is appreciated!

// Can be assigned properly in blueprints
	UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, BlueprintReadWrite, Category = "Inventory")
	TSubclassOf<ACollectableObject> EmptySlot;
// Cannot be assigned properly in blueprints
	UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, BlueprintReadWrite, Category = "Inventory")
	ACollectableObject* EmptySlot;
1 Like

Excellent answer - simple and concise. Cheers!

TSubclassOf<…> (or UClass) is a pointer to the class datatype (like your blueprint asset) and ACollectableObject* would point to an existing actor in your scene created using this type

You would want a TSubclassOf because you are taking in a blueprint asset (i.e. you class type) and then create an instance of this actor in the scene when you need it

UPROPERTY()
TSubclassOf<ACollectableObject> EmptySlotClass;

// ...
UWorld* World = ();
FVector Location(0, 0, 0);
ACollectableObject* EmptySlot = World->SpawnActor(EmptySlotClass, NAME_None, &Location);
1 Like

Sorry that I have to reopen this issue, but I was not able to test the solution right away. Once I got around to doing so, I realised that “SpawnActor” can only return of type AActor and that when casting to ACollectableObject from the spawned actor, my editor crashes - any idea why this could be?

You can use NewObject:

ACollectableObject* EmptySlot = NewObject<ACollectableObject>(this, ACollectableObject::StaticClass());

Small correction, UClass* don’t point to blueprint asset, it point to identifier of class generated from blueprint asset. Blueprint asset is represented by UBlueprint class