UE4 C++学习笔记之使用UMG(上)

任务:使用UMG创建UI,并将其显示在游戏界面

第一步:创建相应的控件蓝图类并编辑

第二步、以PlayController为基类,创建新的C++类,命名为MainPlayerController,在该类中实现调用UI

MainPlayerController.h代码如下:

// Fill out your copyright notice in the Description page of Project Settings.

#pragma once

#include "CoreMinimal.h"
#include "GameFramework/PlayerController.h"
#include "MainPlayerController.generated.h"

/**
 * 
 */
UCLASS()
class LEARNTEST_API AMainPlayerController : public APlayerController
{
	GENERATED_BODY()

public:
        //用户控件类族,可在蓝图中编辑
	UPROPERTY(EditAnywhere,BlueprintReadWrite)
	TSubclassOf<UUserWidget> HUDAsset;

        //用户控件类
	class UUserWidget* HUD;

private:

        //重写BeginPlay函数以调用UI
	virtual void BeginPlay() override;
	
};

MainPlayerController.cpp代码如下:

// Fill out your copyright notice in the Description page of Project Settings.


#include "MainPlayerController.h"
#include "Blueprint\UserWidget.h"

void AMainPlayerController::BeginPlay()
{
	Super::BeginPlay();

	if (HUDAsset)
	{
            //给自定义的用户界面控件赋值
    	    HUD = CreateWidget<UUserWidget>(this, HUDAsset);
	}

	if (HUD)
	{
            //将UI添加到视口,即游戏界面
            HUD->AddToViewport();
	}
}

第三步:以MainPlayerController类为基类,创建蓝图类MyMainPlayerController,并在该蓝图类和GameMode中进行相关设置

然后,运行游戏,就可以看到UI了,效果如下:

猜你喜欢

转载自blog.csdn.net/weixin_44928892/article/details/108173440