Unreal Engine 4 C++ 动态加载UMG界面
最近研究了一下Unreal Engine4,本人不太习惯蓝图打开界面,就研究了下用C++来打开、显示界面。
好记性不如烂笔头啊,还是记录一下!
1.添加UMG依赖
在你的工程下找到以下文件 :
- YourProject.Build.cs
添加如下代码:
PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore", "UMG", "Slate", "SlateCore" });
添加后的完整文件:
- YourProject.Build.cs
// Fill out your copyright notice in the Description page of Project Settings.
using UnrealBuildTool;
public class YourProject : ModuleRules
{
public YourProject(TargetInfo Target)
{
PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore", "UMG", "Slate", "SlateCore" });
PrivateDependencyModuleNames.AddRange(new string[] { });
// Uncomment if you are using Slate UI
// PrivateDependencyModuleNames.AddRange(new string[] { "Slate", "SlateCore" });
// Uncomment if you are using online features
// PrivateDependencyModuleNames.Add("OnlineSubsystem");
// To include OnlineSubsystemSteam, add it to the plugins section in your uproject file with the Enabled attribute set to true
}
}
在你的工程下找到以下文件 :
- YourProject.h
添加如下代码:
#include "Runtime/UMG/Public/UMG.h"
#include "Runtime/UMG/Public/UMGStyle.h"
#include "Runtime/UMG/Public/Slate/SObjectWidget.h"
#include "Runtime/UMG/Public/IUMGModule.h"
#include "Runtime/UMG/Public/Blueprint/UserWidget.h"
添加后的完整文件:
- YourProject.Build.cs
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "Engine.h"
#include "Runtime/UMG/Public/UMG.h"
#include "Runtime/UMG/Public/UMGStyle.h"
#include "Runtime/UMG/Public/Slate/SObjectWidget.h"
#include "Runtime/UMG/Public/IUMGModule.h"
#include "Runtime/UMG/Public/Blueprint/UserWidget.h"
2.创建一个界面
创建一个蓝图控件,取名为Test,如图:
拖拽几个测试控件,如图:
3.添加代码
- YourGameMode.h
#pragma once
#include "GameFramework/GameMode.h"
#include "Blueprint/UserWidget.h"
#include "YourGameMode.generated.h"
/**
*
*/
UCLASS()
class YOURGAMEMODE_API AYourGameMode : public AGameMode
{
GENERATED_BODY()
public:
// 开始游戏
virtual void StartPlay() override;
private:
/** 在游戏开始时我们将作为菜单使用的控件类。 */
UPROPERTY(EditAnywhere)
TSubclassOf<UUserWidget> StartingWidgetClass;
/** 用作为界面的实例。 */
UPROPERTY(EditAnywhere)
UUserWidget* CurrentWidget;
};
- YourGameMode.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "YourGameProject.h"
#include "YourGameModeGameMode.h"
// 开始游戏
void AYourGameMode::StartPlay()
{
Super::StartPlay();
/** 游戏开始后弹出界面 */
StartingWidgetClass = LoadClass<UUserWidget>(NULL, TEXT("Blueprint'/Game/UI/Test.Test_C'"));
if (StartingWidgetClass != nullptr)
{
CurrentWidget = CreateWidget<UUserWidget>(GetWorld(), StartingWidgetClass);
if (CurrentWidget != nullptr)
{
CurrentWidget->AddToViewport();
}
}
}
注意:这里有个大坑,动态加载UClass时需要在代码结尾增加“_C”
StartingWidgetClass = LoadClass<UUserWidget>(NULL, TEXT("Blueprint'/Game/UI/Test.Test_C'"));
4.编译测试
编译后可直接运行,如果成功显示出界面:
成功加载界面。