游戏中快速创建蓝图:
1.新增一个空的项目
2.创建项目成功后创建一个继承HUD的UE类,C++代码
重新编译
PS:如果没有Rider,则手动增加FastUMGHUD.h和.cpp否则工程里不会显示C++类的目录
FastUMGHUD.结构如下:
代码如下:
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/HUD.h"
#include "FastUMGHUD.generated.h"
/**
*
*/
UCLASS()
class FASTUMG_API AFastUMGHUD : public AHUD
{
GENERATED_BODY()
public:
virtual void BeginPlay() override;
};
// Fill out your copyright notice in the Description page of Project Settings.
#include "FastUMGHUD.h"
#include "Blueprint/UserWidget.h"
#include "Blueprint/WidgetBlueprintLibrary.h"
void AFastUMGHUD::BeginPlay()
{
Super::BeginPlay();
UE_LOG(LogTemp,Warning,TEXT("Fast UMG"));
if(const auto UserWidgetClass = LoadClass<UUserWidget>(nullptr,TEXT("/Game/WBP_Main.WBP_Main_C")))
{
if(const auto MainWidget = UWidgetBlueprintLibrary::Create(GetWorld(),UserWidgetClass,nullptr))
{
MainWidget->AddToViewport();
}
}
}
3.创建继承GameModeBase的FastUMGGameModeBase,C++代码
4.在内容目录右键创建一个蓝图继承FastUMGGameModeBase C++类
5.设置GameMode模式,修改hud代码进行打印测试。
打开项目设置
双击打开FastUMGMode蓝图,hud改成FastUMGHUD
修改cpp代码测试输出
点击实时编译
点击运行,打印输出
6.创建界面蓝图
蓝图结构
修改AFastUMGHUD代码通过代码创建蓝图
#include "FastUMGHUD.h"
#include "Blueprint/UserWidget.h"
#include "Blueprint/WidgetBlueprintLibrary.h"
void AFastUMGHUD::BeginPlay()
{
Super::BeginPlay();
UE_LOG(LogTemp,Warning,TEXT("Fast UMG"));
if(const auto UserWidgetClass = LoadClass<UUserWidget>(nullptr,TEXT("/Game/WBP_Main.WBP_Main_C")))
{
if(const auto MainWidget = UWidgetBlueprintLibrary::Create(GetWorld(),UserWidgetClass,nullptr))
{
MainWidget->AddToViewport();
}
}
}
此时编译代码会报错
在Build.cs里增加
编译好运行会打印出hud代码里的输出
7.增加界面逻辑的c++类
蓝图设置父类为WBP_Main
WBP_Main.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "Blueprint/UserWidget.h"
#include "Components/Button.h"
#include "WBP_Main.generated.h"
/**
*
*/
UCLASS()
class FASTUMG_API UWBP_Main : public UUserWidget
{
GENERATED_BODY()
public:
virtual void NativeConstruct() override;
UPROPERTY(meta = (BindWidget))
class UButton* ButtonClick;
UFUNCTION()
void OnButtonClicked();
};
WBP_Main.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "WBP_Main.h"
void UWBP_Main::NativeConstruct()
{
Super::NativeConstruct();
ButtonClick->OnClicked.AddDynamic(this, &UWBP_Main::OnButtonClicked);
}
void UWBP_Main::OnButtonClicked()
{
UE_LOG(LogTemp, Warning, TEXT("Click"));
}
此时就完成了一个创建界面蓝图,也实现了界面蓝图点击按钮事件。