I have an actor with a bunch of sub-component trigger volumes. All the trigger volumes do the same thing when something hits them, so I want to use only one collision function for all of them.
However, I do need to know exactly which volume was collided with so that I can run functions pertaining to it. So how would I get the ‘this’ component inside onOverlapBegin() and onOverlapEnd()?
I had a similar situation, so what I did was to create a new component type that inherits from UBoxComponent called UMyTriggerComponent and added a public function to it such as OnBeginTriggerOverlap, you can decide to make it implementable by BP or not.
Then in my BP actor class where I just register and unregistered the overlap function. I registered them in BeginPlay and unregister them in EndPlay (you might want to customize where to register/unregister the handlers).
// Register all triggers with their own overlap handlers
TArray<UMyTriggerComponent*> comps;
GetComponents(comps);
for (auto Iter = comps.CreateConstIterator(); Iter; ++Iter)
{
if (UMyTriggerComponent* TriggerComponent = Cast<UMyTriggerComponent>(*Iter))
{
TriggerComponent->OnComponentBeginOverlap.AddDynamic(TriggerComponent, &UTriggerComponent::OnBeginTriggerOverlap);
}
}
// Unregister all overlap events
TArray<UMyTriggerComponent*> comps;
GetComponents(comps);
for (auto Iter = comps.CreateConstIterator(); Iter; ++Iter)
{
if (UMyTriggerComponent* TriggerComponent = Cast<UMyTriggerComponent>(*Iter))
{
TriggerComponent->OnComponentBeginOverlap.RemoveDynamic(TriggerComponent, &UTriggerComponent::OnBeginTriggerOverlap);
}
}
Just to confirm: essentially a class is used to pretend everything is calling the same function when they’re in fact just calling their local copies, right?
What I’m doing is register a function of the component itself to catch the event and not the owning actor, the owning actor just registers/unregisters the events, this way you know exactly which component got the overlap event because the actual component will get noticed.