Note: the definition of OneshotBindLambda
is not written inside .cpp file since template
causes problems and must only be used in .h files
// *.h file
#pragma once
class FUtility {
public:
template <typename DelegateType, typename LambdaType>
static void OneshotBindLambda(DelegateType& Delegate, LambdaType&& LambdaFunction) {
TSharedPtr<FDelegateHandle> Handle = MakeShared<FDelegateHandle>();
// Bind the lambda function to the delegate
*Handle = Delegate.AddLambda([Handle, &Delegate, LambdaFunction]() {
LambdaFunction();
if (Handle.IsValid()) // Remove this delegate handle to make it one-shot
Delegate.Remove(*Handle);
});
}
};
Usage:
DECLARE_MULTICAST_DELEGATE(FMyDelegate);
FMyDelegate MyDelegate;
FUtility::OneshotBindLambda(MyDelegate, []{
GEngine->AddOnScreenDebugMessage(-1, 15.0f, FColor::Yellow, TEXT("This will be invoked only once!"));
});