docs.unrealengine.com/5.0/zh-CN/q…
新建一个基于actor 的c++类
基于actorC++类新建一个蓝图,可在蓝图中调用父类方法
Countdown.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "Components/TextRenderComponent.h"
#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "Countdown.generated.h"
UCLASS()
class HOWROUMG_API ACountdown : public AActor
{
GENERATED_BODY()
public:
// Sets default values for this actor's properties
ACountdown();
protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
public:
// Called every frame
virtual void Tick(float DeltaTime) override;
//倒数的运行时长(以秒计)
UPROPERTY(EditAnywhere)
int32 CountdownTime;
UTextRenderComponent* CountdownText;
void UpdateTimerDisplay();
void AdvanceTimer();
//为了让非程序员调用C++函数,并用 **蓝图** 对其进行覆盖,需对 `Countdown.h` 进行以下修改
UFUNCTION(BlueprintNativeEvent)
void CountdownHasFinished();
virtual void CountdownHasFinished_Implementation();
FTimerHandle CountdownTimerHandle;
};
Countdown.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "TimerManager.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.
//将此Actor设为逐帧调用Tick()。如无需此功能,可关闭以提高性能。
PrimaryActorTick.bCanEverTick = false;
CountdownText = CreateDefaultSubobject<UTextRenderComponent>(TEXT("CountdownNumber"));
CountdownText->SetHorizontalAlignment(EHTA_Center);
CountdownText->SetWorldSize(150.0f);
RootComponent = CountdownText;
CountdownTime = 3;
}
// Called when the game starts or when spawned
void ACountdown::BeginPlay()
{
Super::BeginPlay();
//向新更新的函数添加调用,初始化 ACountdown::BeginPlay 中显示的文本,并设置逐秒前进和更新倒数的定时器:
UpdateTimerDisplay();
GetWorldTimerManager().SetTimer(CountdownTimerHandle, this, &ACountdown::AdvanceTimer, 1.0f, true);
//note:由于在 ACountdown::BeginPlay 期间设置倒数,而非 ACountdown::ACountdown 期间,因此默认文本会在 关卡编辑器 中显示。
}
// Called every frame
void ACountdown::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
}
//更新文本显示,以显示剩余时间。时间结束时,则显示为零。此代码应在游戏中首次生成 ACountdown 时运行,在 CountdownTime 变量为零前每秒运行一次。
void ACountdown::UpdateTimerDisplay()
{
// CountdownText->SetText(FString::FromInt(FMath::Max(CountdownTime, 0)));
CountdownText->SetText(FText::FromString(FString::FromInt(CountdownTime)));
}
void ACountdown::AdvanceTimer()
{
--CountdownTime;
UpdateTimerDisplay();
if (CountdownTime < 1)
{
//倒数完成,停止运行定时器。
GetWorldTimerManager().ClearTimer(CountdownTimerHandle);
//定时器结束时,执行要执行的特殊操作。
CountdownHasFinished();
}
}
void ACountdown::CountdownHasFinished_Implementation()
{
//改为特殊读出
CountdownText->SetText(FText::FromString("GO!"));
}