c++获取umg ue_UE4-UMG与c++交互
UE4-UMG与c++交互
创建工程
打开VS
修改 项目名.Build.cs文件
添加”UMG”,”Slate”,”SlateCore”
image.png
修改 项目名.h文件
添加
#include "Runtime/UMG/Public/UMG.h"
include "Runtime/UMG/Public/UMGStyle.h"
include "Runtime/UMG/Public/Blueprint/UserWidget.h"
include "Runtime/UMG/Public/Slate/SObjectWidget.h"
include "Runtime/UMG/Public/IUMGModule.h"
image.png
回到虚幻编辑器,创建C++类,从UserWidget派生
image.png
创建组件蓝图(Widget Blueprint),并添加文本控件
image.png
image.png
打开第5步创建的C++类,在头文件中新建文本变量,源文件中添加显示文本的代码
image.png
image.png
回到虚幻引擎编辑器,打开第6步创建的组件蓝图,修改其父类
image.png
创建显示组件实例,分为两种方法,一种是在C++中通过代码创建,另一种是在蓝图中创建。
(1) c++代码创建
l 创建HUD类,并修改类的代码,此处以“阿凡亚麻达”的代码为例
|
在SlAiMenuHUDWidget.h****文件中:
// Fill out your copyright notice in the Description page of Project Settings.
pragma once
include "CoreMinimal.h"
include "GameFramework/HUD.h"
include "SlAiMenuHUD.generated.h"
/**
*/
UCLASS()
class SLAICOURSE_API ASlAiMenuHUD : public AHUD
{
GENERATED_BODY()
public:
ASlAiMenuHUD();
class USlAiMenuHUDWidget* MenuHUDWidget;
TSubclassOf MenuHUDWidgetClass;
};
|
|
在SlAiMenuHUD.cpp****中:
// Fill out your copyright notice in the Description page of Project Settings.
include "SlAiMenuHUD.h"
include "SlAiMenuHUDWidget.h"
include "UObject/ConstructorHelpers.h"
ASlAiMenuHUD::ASlAiMenuHUD () {
if (GEngine && GEngine->GameViewport)
{
// 找到蓝图类,可以在编译器中点击SlAiMenuHUDWidget文件,然后按下ctrl+c即可获取该路径名,注意,需要加_C
static ConstructorHelpers::FClassFinder MenuHUDWidgetBP ( TEXT ( "WidgetBlueprint'/Game/UI/SlAiMenuHUDWidget.SlAiMenuHUDWidget_C'" ) );
if (MenuHUDWidgetBP.Succeeded ()) {
MenuHUDWidgetClass = MenuHUDWidgetBP.Class; // 得到class
}
MenuHUDWidget = CreateWidget(GetWorld()->GetGameInstance(),MenuHUDWidgetClass );
if (MenuHUDWidget != nullptr) {
MenuHUDWidget->AddToViewport ();
}
}
}
|
l 把刚刚创建的HUD类设置为GAMEMODE里的默认HUD(需要自己创建GameMode,如何创建GameMode请查看相关官方文档)
image.png
(2) 蓝图创建方法
l 打开关卡蓝图,并在里面进行配置
image.png
编译,并运行测试!
image.png
PS:UMG与C++的交互到步骤8就完成了,也就是只要创建widget blurprint(控件蓝图)以及派生自UserWidget的C++类,将WidgetBlueprint中的父类设为创建的C++类,随后就可以在C++类中去获取WidgetBlueprint中的控件了。
更多推荐
所有评论(0)