How to use an ActorComponent to attach a UBoxComponents to the parent actor to create overlap events

Hi Everyone,

Essentially what I am trying to create is an Actor (which will be “possessed” object) in a horror mansion game (which can have different static mesh components swapped out ie. vase, books, shelf, etc.) which I can add an Actor Component to that will generate custom physics events.

I can create the custom physics attached to the actor itself, but I want to make it where the level designer can add and remove different physics applications to the base actor with the “possessed actor physics components”.

So far I am able to call physics, through the possessed actor physics component using…

GetOwner()->GetComponents<UStaticMeshComponent>(ActorComponents);

And then calling…

PossessedComp->AddForce(ForceDirection * ForcePower * PossessedComp->GetMass());

and everything works fine.

However I would like to create a UBoxComponent, attached to the actor, where if the player in the level overlaps the box component it would then call the AddForce function.

However I create the UBoxComponent in the “possessed actor component”, but can’t seem to attach it to the actor Root component.

So in the actor component constructor…

PossessionOverlapComp = CreateDefaultSubobject<UBoxComponent>(TEXT("PossessionOverlapBoxComp"));
PossessionOverlapComp->SetHiddenInGame(false);
PossessionOverlapComp->SetBoxExtent(PossessionOverlapCompBoxSize);
PossessionOverlapComp->SetupAttachment(GetOwner()->GetRootComponent());

However I get an exception thrown with…

PossessionOverlapComp->SetupAttachment(GetOwner()->GetRootComponent());

And the debugger states…

“Exception thrown at 0x00007FFB12389194 (UE4Editor-HRM.dll) in UE4Editor.exe: 0xC0000005: Access violation reading location 0x0000000000000148.”

Any thoughts on attaching a UBoxComponent from an Actor Component to the actual Actor?

Most likely your GetOwner() is not available yet in the constructor…

Related links :

Thank you @bo0olean !

That worked. I called GetOwner() on begin play and I was able to access the Root Component.

Just want to give you a warning, a component inside a component is against the engine’s intended use for components. Components should ONLY ever be created on an actor. What you have done here will not even register the component properly with the actor.

1 Like

Thank you !

Your point was extremely helpful, and makes since now that I have worked through the Engine.

I could attach a UBoxComponent to an Actor through the actor component, but certain features of the UBoxComponent such as SetHiddenInGame(false) and attaching to the actor root component would either not function at all, or act funny, compared to simply adding the box component to the actor itself.

Thank you very much for your time answering my question and your insight. That is why I love working with this community.

1 Like