Cannot add a Component to an Actor

In my Actor subclass ATrack, I have a method that takes in a TSubclassOf(UPiece) called NextPiece. UPiece is derived from StaticMeshComponent.

Here’s my code:

void ATrack::ArrangeNextPiece(TSubclassOf<class UPiece> NextPiece)
{
	auto CurrentPiece = NextPiece;
	FString CurrentPieceName = CurrentPiece->GetName();
	UE_LOG(LogTemp, Warning, TEXT("CurrentPieceName: %s"), *CurrentPieceName)
	UPiece* MyTrackPiece = NewObject<UPiece>(CurrentPiece)

	UE_LOG(LogTemp, Warning, TEXT("MyTrackPiece: %s"), *MyTrackPiece->GetName());
	
	// MyTrackPiece->SetWorldLocationAndRotation(NextPieceLocation, NextPieceRotation, false);
}

This runs fine and logs out this:

253086-capture.png

But the piece does not appear in the hierarchy, and if I uncomment the SetWorldLocationAndRotation() method, it hard-crashes.

If I change the NewObject line to this…

UPiece* MyTrackPiece = NewObject<UPiece>(this, CurrentPiece)

…then it hard-crashes.

It seems that the piece will be created happily enough, but my ATrack actor refuses to accept a new component?

No suggestions? I feel like this should be easier than it is. Is NewObject even the correct function? It seems like it does nothing.

First I highly suggest not using Auto for this, it only servers to confuse you in debugging. The correct form of NewObject should be:

UPiece * MyTrackPiece = NewObject<UPiece>(this, CurrentPeice);

This is what I use everywhere. You say this is crashing on you, than run Visual Studio in Debug Mode, the Hard crash should trigger a break point. Use the stack trace to hunt down the problem. Hard crashes are usually caused by the object you are calling the function on being null (“this” probably is null).

After creating the peice you need to Attach it to the actor using

MyTrackPeice->AttachTo(this->GetRootRcomponent());
MyTrackPeice->RegisterComponent();

Also don’t forget to register your component. If you are doing this with a Server In mind you run the function on the server only, and make sure replication for your component is turned on.