创建一个可以使用时间的物体
先选择添加代码到项目,创建继承自Actor的CountDown
#pragma once
#include "GameFramework/Actor.h"
#include "CountDown.generated.h"
UCLASS()
class MYTEST_API ACountDown : public AActor
{
GENERATED_BODY()
public:
// Sets default values for this actor's properties
ACountDown();
//初始设置时间
int32 CountDownTime;
//显示字体内容
UTextRenderComponent* CountdownText;
//更新时间显示
void UpdateTimerDisplay();
//时间衰退
void AdvanceTimer();
//当时间结束
void CountdownHasFinished();
//定时器的手柄
FTimerHandle CountdownTimerHandle;
virtual void BeginPlay() override;
};
.cpp文件
// Fill out your copyright notice in the Description page of Project Settings.
#include "MyTest.h"
#include "CountDown.h"
// Sets default values
ACountDown::ACountDown()
{
// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = false;
//创建字体显示
CountdownText = CreateDefaultSubobject<UTextRenderComponent>(TEXT("CountdownNumber"));
CountdownText->SetHorizontalAlignment(EHTA_Center);//设置水平中心对齐
CountdownText->SetWorldSize(150.0f);//设置字体大小
CountdownText->AttachTo(RootComponent);//将该字体附在根节点下
RootComponent = CountdownText;//设置为根节点
CountDownTime = 3;
}
//设置显示的内容为CountDownTime
void ACountDown::UpdateTimerDisplay()
{
CountdownText->SetText(FString::FromInt(FMath::Max(CountDownTime, 0)));
}
void ACountDown::AdvanceTimer()
{
--CountDownTime;
UpdateTimerDisplay();
if (CountDownTime < 1)
{
//当时间小于1,清除定时器手柄
GetWorldTimerManager().ClearTimer(CountdownTimerHandle);
CountdownHasFinished();//计时已经结束
}
}
void ACountDown::CountdownHasFinished()
{
CountdownText->SetText(TEXT("GO"));
}
void ACountDown::BeginPlay()
{
Super::BeginPlay();
//更新显示
UpdateTimerDisplay();
//设置时间手柄CountdownTimerHandle调用AdvanceTimer
GetWorldTimerManager().SetTimer(CountdownTimerHandle, this, &ACountDown::AdvanceTimer, 1.0f, true);
}