在上一例子中,创建一个Widget还需要通过一个Actor类对象,在运行程序之前还得把它拖入世界关卡中,实在是太麻烦了。
能不能让这个UI的出现是通过按键绑定弹出?就如同我们玩游戏的效果一样?
这一例子中进行尝试。
还是利用《创建UserWidget(1)》中的UI蓝图,创建一个新的Character类。
第一步,先进行按键绑定,我想用shit+q来呼出UI界面。
第二步,进行代码上的绑定。
Character类的头文件代码:
1 // Fill out your copyright notice in the Description page of Project Settings.
2
3 #pragma once
4
5 #include "CoreMinimal.h"
6 #include "GameFramework/Character.h"
7 #include "Blueprint/UserWidget.h"
8 #include "MyCharacter.generated.h"
9
10 UCLASS()
11 class MYPROJECT2_API AMyCharacter : public ACharacter
12 {
13 GENERATED_BODY()
14
15 public:
16 // Sets default values for this character's properties
17 AMyCharacter();
18
19 protected:
20 // Called when the game starts or when spawned
21 virtual void BeginPlay() override;
22
23 public:
24 // Called every frame
25 virtual void Tick(float DeltaTime) override;
26
27 // Called to bind functionality to input
28 virtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override;
29
30 public:
31
32 UPROPERTY(EditAnywhere,BlueprintReadWrite,Category = "UI")
33 TSubclassOf<UUserWidget> widget;
34
35
36 UUserWidget* myWidget;
37 void getUI();
38 };
因为要使用CreateWidget方法来创建UI的实例,第二个参数位必须为TSubclassof<T>模板类型。getUI方法就是用来显示出UI界面的。
Character类的源文件代码:
1 // Fill out your copyright notice in the Description page of Project Settings.
2
3
4 #include "MyCharacter.h"
5 #include "Kismet/GameplayStatics.h"
6
7 // Sets default values
8 AMyCharacter::AMyCharacter()
9 {
10 // Set this character to call Tick() every frame. You can turn this off to improve performance if you don't need it.
11 PrimaryActorTick.bCanEverTick = true;
12
13 }
14
15 // Called when the game starts or when spawned
16 void AMyCharacter::BeginPlay()
17 {
18 Super::BeginPlay();
19 myWidget = CreateWidget<UUserWidget>(GetWorld(), widget);
20 }
21
22 // Called every frame
23 void AMyCharacter::Tick(float DeltaTime)
24 {
25 Super::Tick(DeltaTime);
26
27 }
28
29 // Called to bind functionality to input
30 void AMyCharacter::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)
31 {
32 Super::SetupPlayerInputComponent(PlayerInputComponent);
33 PlayerInputComponent->BindAction("UI", IE_Pressed, this, &AMyCharacter::getUI);
34 }
35
36 void AMyCharacter::getUI()
37 {
38 if (myWidget) {
39 myWidget->AddToViewport();
40 }
41 }
第一个参数为拥有者,这个UI实例创建之后,其拥有者是世界关卡。
1 myWidget = CreateWidget<UUserWidget>(GetWorld(), widget);
生成AMyCharacter蓝图,并选择好UI类。
GameMode和Default Pawn都要选择成我们的蓝图。
准备工作就绪,效果图如下,按下shift+q,即可呼出UI: