UE使用C++通过定时器启用和停用Tick
写在前面
PrimaryActorTick.bCanEverTick这个赋值为true也好,false也好,好像只能在构造函数里面起作用,应该就是当在构造函数里面执行
PrimaryActorTick.bCanEverTick = true;
之后,UE会在BeginPlay阶段自动执行
PrimaryActorTick.RegisterTickFunction(GetLevel());
就是自动注册了Tick方法。
Tick注销的办法是
PrimaryActorTick.UnRegisterTickFunction();
做了一段Actor自动上升的控制,通过计时器不断将Tick方法进行注册和注销,让Actor一会上升,一会儿停止。
启用和停用Tick的代码示例
.h文件代码:
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "DrawLine3D.generated.h"
UCLASS()
class LEARNINGBP00_API ADrawLine3D : public AActor
{
GENERATED_BODY()
private:
UStaticMesh* SM_Knot;
UMaterial* matA;
UStaticMeshComponent* StaticMeshA;
public:
ADrawLine3D();
protected:
virtual void BeginPlay() override;
public:
virtual void Tick(float DeltaTime) override;
FTimerHandle timeHandleA;
FTimerHandle timeHandleB;
//注册Tick的方法
void RegisterTick();
//注销Tick的方法
void UnRegisterTick();
};
.cpp文件代码:
#include "DrawLine3D.h"
ADrawLine3D::ADrawLine3D()
{
SM_Knot = Cast<UStaticMesh>(StaticLoadObject(UStaticMesh::StaticClass(), NULL, TEXT("/Game/FBX/Knot")));
matA = Cast<UMaterial>(StaticLoadObject(UMaterial::StaticClass(), NULL, TEXT("/Game/Material/MatA")));
StaticMeshA = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("StaticMeshA"));
StaticMeshA->SetStaticMesh(SM_Knot);
StaticMeshA->SetMaterial(0, matA);
PrimaryActorTick.bCanEverTick = true;//这个应该是只能在构造函数里面起作用。
}
void ADrawLine3D::BeginPlay()
{
Super::BeginPlay();
//通过定时器设置每隔6秒注销Tick
GetWorldTimerManager().SetTimer(timeHandleA, this, &ADrawLine3D::UnRegisterTick, 6, true, 2);
//通过定时器设置每隔6秒注册Tick
GetWorldTimerManager().SetTimer(timeHandleB, this, &ADrawLine3D::RegisterTick, 6, true, 5);
}
void ADrawLine3D::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
//Actor以每秒10个单位的速度上升
AddActorLocalOffset(FVector(0, 0, 10 * DeltaTime));
}
void ADrawLine3D::RegisterTick()
{
PrimaryActorTick.RegisterTickFunction(GetLevel());
GEngine->AddOnScreenDebugMessage(-256, 2, FColor::Blue, FString("RegisterTick"));
}
void ADrawLine3D::UnRegisterTick()
{
PrimaryActorTick.UnRegisterTickFunction();
GEngine->AddOnScreenDebugMessage(-111, 2, FColor::Red, FString("UnRegisterTick"));
}