标签:学习 override 文件 virtual form creat viewport setting game
我们先创建一个UserWidget的蓝图,起名BP_Widget。
在我们的Widget蓝图中添加一个Button,并为Button添加一个Click的方法。
方法很简单,当Button被按下的时候,打印"Hello Widget"即可。
创建一个继承自Actor类的自定义类,用于读取和创建UserWidget类的实例。
头文件如下:
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/Actor.h" 7 #include "WidgetActor.generated.h" 8 9 UCLASS() 10 class MYPROJECT2_API AWidgetActor : public AActor 11 { 12 GENERATED_BODY() 13 14 public: 15 // Sets default values for this actor‘s properties 16 AWidgetActor(); 17 18 protected: 19 // Called when the game starts or when spawned 20 virtual void BeginPlay() override; 21 22 public: 23 // Called every frame 24 virtual void Tick(float DeltaTime) override; 25 26 public: 27 UPROPERTY(EditAnywhere,BlueprintReadWrite,Category="UI") 28 TSubclassOf<UUserWidget> widgetChoice; 29 30 31 UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "UI") 32 class UStaticMeshComponent* myStaticMesh; 33 };
源文件如下:
1 // Fill out your copyright notice in the Description page of Project Settings. 2 3 4 #include "WidgetActor.h" 5 #include "Blueprint/UserWidget.h" 6 7 // Sets default values 8 AWidgetActor::AWidgetActor() 9 { 10 // Set this actor 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 16 // Called when the game starts or when spawned 17 void AWidgetActor::BeginPlay() 18 { 19 Super::BeginPlay(); 20 21 22 if (widgetChoice) { 23 UUserWidget* myWidget = CreateWidget<UUserWidget>(GetWorld(), widgetChoice); 24 if (myWidget) { 25 myWidget->AddToViewport(); 26 GetWorld()->GetFirstPlayerController()->bShowMouseCursor = true; 27 } 28 } 29 30 } 31 32 // Called every frame 33 void AWidgetActor::Tick(float DeltaTime) 34 { 35 Super::Tick(DeltaTime); 36 37 }
把AWidgetActor类拖入关卡中,并选取我们之前做好的Widget类的蓝图。
效果如下:
基于C++代码的UE4学习(十一)—— 创建UserWidget(1)
标签:学习 override 文件 virtual form creat viewport setting game
原文地址:https://www.cnblogs.com/dlak/p/13287739.html