Casting to spawned actor causes editor to crash

I am trying to create a new instance of a class in my scene. I instantiate an actor based on a blueprint, then try to cast it to the corresponding class. When I compile the solution, my editor crashes. Anyone know why this could be?

	// Item that is used for empty slots in the inventory - makes it easier to switch between item slots and allows for more customisation by the designer
	UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = "Inventory", Meta = (AllowPrivateAccess = "true"))
	TSubclassOf<class ACollectableObject> EmptySlotClass;
	ACollectableObject* EmptySlot = nullptr;

// In cpp...
// Spawn an empty slot actor into the world, so that we can reference it
	EmptySlot = Cast<ACollectableObject>(this->GetWorld()->SpawnActor(EmptySlotClass));

ACollectableObject is derived from AActor base class. Thank you in advance!

This stops the game from crashing! Thanks - however, even after I assign the blueprint in the editor, the empty slot class seems to get back a null reference and the cast does not happen. Any idea why this could be?

Maybe you’ve forgotten to assign EmptySlotClass a value in the blueprint. In any case, always try and remember to protect against null pointers,enclose your spawning code by a

if(EmptySlotClass){
EmptySlot = Cast<>();
} else { UE_LOG(LogTemp, Warning, TEXT("Mr Designer, please assign BP for the empty slot"))

You can checkout ensure / check macros as well, they are asserts and can prevent a crash and you can use them to logout messages to alert you of a nullptr…

Are you trying to use the Blueprint-assigned value in the constructor? If so, it won’t be available yet and you can rather use “OnConstruction”.