Unreal uses events for notifying classes about things that happen in the game world in an efficient manner. Events and delegates are useful to ensure that these notifications can be issued in a way which minimizes class coupling, and allows arbitrary classes to subscribe to be notified.
We will cover the following recipes in this chapter:
Some Actor
and Component
classes provided with Unreal include event handlers in the form of virtual functions. This recipe will show you how to customize those handlers by overriding the virtual function in question.
Actor
in the Editor. Call it MyTriggerVolume
.UPROPERTY() UBoxComponent* TriggerZone; UFUNCTION() virtual void NotifyActorBeginOverlap(AActor* OtherActor) override; UFUNCTION() virtual void NotifyActorEndOverlap(AActor* OtherActor) override;
void AMyTriggerVolume::NotifyActorBeginOverlap(AActor* OtherActor) { GEngine->AddOnScreenDebugMessage(-1, 1, FColor::Red, FString::Printf(TEXT("%s entered me"),*(OtherActor->GetName()))); } void AMyTriggerVolume::NotifyActorEndOverlap(AActor* OtherActor) { GEngine->AddOnScreenDebugMessage(-1, 1, FColor::Red, FString::Printf(TEXT("%s left me"), *(OtherActor->GetName()))); }
MyTriggerActor
into the level. Verify that overlap/touch events are handled by walking into the volume, and seeing the output printed to the screen:UPROPERTY
to hold a reference to our component subobject. We then create two UFUNCTION
declarations. These are marked as virtual
and override
so that the compiler understands we want to replace the parent implementation, and that our function implementations can be replaced in turn.FString::printf
to create an FString
from some preset text, and substitute some data parameters.FString
OtherActor->GetName()
returns, and is dereferenced using the *
operator before being passed into FString::Format
. Not doing this results in an error.FString
is then passed to a global engine function, AddOnScreenDebugMessage
.-1
tells the engine that duplicate strings are allowed, the second parameter is the length of time the message should be displayed for in seconds, the third argument is the color, and the fourth is the actual string to print itself.UpdateOverlaps
function will call NotifyActorBeginOverlap
, and the virtual function dispatch will call our custom implementation.18.118.184.155