UE4-对话系统
事先准备:创建WidgetBlueprint(控件蓝图)、MyUserWidget类(派生于UserWidget类)并使其交互,具体方法参考 UE4-UMG与c++交互。
对话系统搭建步骤:
- 创建Actor类,用来控制对话内容的显示。
我创建了WidgetMng.h和WidgetMng.cpp文件。
- 将自己创建的UserWidget(用户组件)在游戏开始时加载到视口。
这一步需要分成几个小部分:
(1) 在WidgetMng.h中加入2个变量、将用户组件加载到视口的方法:
代码为:
|
public:
/** 在游戏开始时调用。 */
virtual void BeginPlay() override;
/** 移除当前菜单控件并且如果可能,从指定类中创建新控件。 */
UFUNCTION(BlueprintCallable, Category = "UMG Game")
void ChangeMenuWidget(TSubclassOf<UUserWidget> NewWidgetClass);
protected:
/** 在游戏开始时我们将作为菜单使用的控件类。 */
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "UMG Game")
TSubclassOf<UUserWidget> StartingWidgetClass;
/** 用作为菜单的控件实例。 */
UPROPERTY()
UUserWidget* CurrentWidget;
|
(2) 包含所需UserWidget的头文件
<pre style="margin-left:54.0pt">#include "Blueprint/UserWidget.h"</pre>
(3) 在WidgetMng.cpp中编写方法,这个方法会先移除视口中的已存的UserWidget并将我们的UserWidget添加到视口中。
|
void AWidgetMng::ChangeMenuWidget(TSubclassOf<UMyUserWidget> NewWidgetClass)
{
if (CurrentWidget != nullptr)
{
CurrentWidget->RemoveFromViewport();
CurrentWidget = nullptr;
}
if (NewWidgetClass != nullptr)
{
CurrentWidget = CreateWidget<UMyUserWidget>(GetWorld(), NewWidgetClass);
if (CurrentWidget != nullptr)
{
CurrentWidget->AddToViewport();
}
}
}
|
(4) 在BeginPlay中去调用
|
void AWidgetMng::BeginPlay()
{
Super::BeginPlay();
ChangeMenuWidget(StartingWidgetClass);
}
|
- 这步开始完成关于定时器的设定
(1) 在WidgetMng.h中加入定时器所需的变量
|
//定时器相关参数
//定时器句柄
FTimerHandle CountdownTimerHandle;
//定时器速率
UPROPERTY(EditAnywhere, Category = "Timer")
float Interveral;
|
(2) 在WidgetMng.CPP的BeginPlay中开启定时器
|
GetWorldTimerManager().SetTimer(CountdownTimerHandle, this, &AWidgetMng::UpdateShowContent, Interveral, true);
|
定时器会在游戏开始时执行,启用名为CountdownTimerHandle的定时器,定时间隔为interval,循环定时,每次到时候调用UpdateShowContent方法。
- 打字机效果的对话显示
(1) 在WidgetMng.h中加入所需变量
|
//对话系统相关参数
//文字索引
int32 index;
//显示文字初始化
void ShowContInitialize();
//显示文字更新
void UpdateShowContent();
//用于输入存放需要显示内容的变量
UPROPERTY(EditAnywhere,Category = "ShowContent")
FString Content;
//用于实际内容显示的变量
FString ShowCont;
//用于显示内容的矩阵
TCHAR* tmpcont;
|
(2) 在WidgetMng.CPP中编写具体方法
|
void AWidgetMng::UpdateShowContent()
{
if (index < Content.Len())
{
ShowCont += tmpcont[index];
CurrentWidget->MyMenuTitle->SetText(FText::FromString(ShowCont));
index += 1;
}
}
void AWidgetMng::ShowContInitialize()
{
index = 0;
tmpcont = Content.GetCharArray().GetData();
}
|
(3) 在BeginPlay中加入关于对话显示的方法,更新后为:
|
void AWidgetMng::BeginPlay()
{
Super::BeginPlay();
ChangeMenuWidget(StartingWidgetClass);
ShowContInitialize();
GetWorldTimerManager().SetTimer(CountdownTimerHandle, this, &AWidgetMng::UpdateShowContent, Interveral, true);
}
|
- 回到虚幻引擎编译文件,将WidgetMng拖入场景中,设置定时器的速率,写入要显示的内容,查看效果。
初步的打字机文字效果完成!