How do you trigger custom C++ code from an animation in Unreal Engine 5?
Adding a new AnimNotify class
Unreal Engine offers a few stock notify types for things like playing audio or triggering particle effects from animation montages, but I'm assuming you need to run some custom C++ code at specific points in an animation. In that case, we can create a new notify type and use this to run any code we'd like.
- Tools > New C++ Class... and create a new C++ class with AnimNotify as its parent. Give it some time for the engine to be recompiled.
- Open up an animation montage and right-click a Notify track to add a new notify. The list should include your recently created custom notify class.
- Override the Notify() function in the newly created .h and .cpp files. Code should look something like below.
CustomAnimNotify.h
#pragma once
#include "CoreMinimal.h"
#include "Animation/AnimNotifies/AnimNotify.h"
#include "CustomAnimNotify.generated.h"
UCLASS()
class YOURPROJECT_API UCustomAnimNotify : public UAnimNotify
{
GENERATED_BODY()
public:
virtual void Notify(USkeletalMeshComponent* MeshComp, UAnimSequenceBase* Animation) override;
};
CustomAnimNotify.cpp
#include "CustomAnimNotify.h"
void UCustomAnimNotify::Notify(USkeletalMeshComponent* MeshComp, UAnimSequenceBase* Animation)
{
if (GEngine)
{
GEngine->AddOnScreenDebugMessage(-1, 10.f, FColor::Yellow, TEXT("Custom AnimNotify triggered!"));
}
}
Save, recompile, reload, and when that animation montage plays it should now print the above message on screen.
Top comments (0)