Download

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:
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?

You need to call RegisterComponent() before doing anything else with it and you also need to use the Actor as the outer (as in the second code example).

Also, be careful about providing object names. If you give an object a duplicate name trouble will arise.



UPiece* MyTrackPiece = NewObject<UPiece>(SomeActor, UPiece::StaticClass());
MyTracePiece->RegisterComponent();


Thanks very much, Jamsh. It turns out the hard crash was caused by a silly error upstream of this function, but thanks for letting me know about that. Much appreciated.