Replace Root Component on an Inherited Class

Hi everyone!

So my question is: is it possible to replace the root component in a subclass if I’ve already changed it in the super class?

To explain more, I have a c++ class inheriting from Actor called BaseInteractable. I made the root component of BaseInteractable a SphereComponent. Now in a subclass of BaseInteractable, BaseInteractable_Child, I am trying to change the root component to a BoxComponent. But I am having issues with it. Does anyone know if a) this is possible to do and b) how I might do this?

Any help or advice is greatly appreciated thanks!

Alright never mind haha. It’s always right after you think you can’t do something that you find the solution.

So apparently the solution was very simple:

SuperClass.h

// Declare a sphere component 
UPROPERTY(VisibleDefaultsOnly, Category = Interact)
class USphereComponent* InteractArea;

SuperClass.cpp

// Create subobject in the constructor
InteractArea = CreateDefaultSubobject<USphereComponent>(TEXT("InteactArea"));
RootComponent = InteractArea;

SubClass.h

// Declare a new component to use as the new root component
UPROPERTY(VisibleDefaultsOnly, Category = Interact)
class UStaticMeshComponent* SM;

SubClass.cpp

// Create the subobject make it the new root component
SM = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("SM"));

// Note that this makes SM the new root but it then attaches the previous root to SM
RootComponent = SM;

/* 
 * The above code makes SM the new root as mentioned, but then it effectually does:
 *      InteractArea->SetupAttachment(GetRootComponent());
 * 
 * At least that's what I'm observing. It could be doing something else.
 */

This is the behavior I was going for, but hopefully others will find this helpful too.

Yes you have to assign a new RootComponent and then call:

InteractArea->DestroyComponent(); // Unregisters and destroys the old RootComponent

Otherwise the old component will still exist and will still interfere with the gameplay which may not always be intended.