网上有人推荐说使用 FPlatformProcess::Sleep(1.0f);

其实使用这种方法会导致整个程序被延迟,并不是我们想要的。

有两种方法模拟延迟,实际上彼此没有区别。

1、在BindLambda中使用FTimerDelegate

FTimerDelegate TimerDelegate;
TimerDelegate.BindLambda([&]
{
UE_LOG(LogTemp, Warning, TEXT("This text will appear in the console 3 seconds after execution"))
});

FTimerHandle TimerHandle;
GetWorld()->GetTimerManager().SetTimer(TimerHandle, TimerDelegate, 3, false);

2. 只使用FTimerHandle

FTimerHandle TimerHandle;
GetWorld()->GetTimerManager().SetTimer(TimerHandle, [&]()
{
UE_LOG(LogTemp, Warning, TEXT("This text will appear in the console 3 seconds after execution"))
}, 3, false);

第二种方法是使用延迟来执行另一个函数。下面的示例使用动态绑定,但您也可以通过BindUFunction进行绑定。

1、如果没有输入参数

FTimerHandle TimerHandle;
GetWorld()->GetTimerManager().SetTimer(TimerHandle, this, &UObject::MethodWithDelay, 3, false);

2、如果有输入参数

int32 ParameterToPass = 100; // You can use any supported variable type

FTimerHandle TimerHandle;
FTimerDelegate TimerDelegate = FTimerDelegate::CreateUObject(this, &UObject::MethodWithDelay, ParameterToPass);
GetWorld()->GetTimerManager().SetTimer(TimerHandle, TimerDelegate, 3, false);