Last active
May 30, 2016 03:05
-
-
Save dorgonman/cbfe159a83ba07f1c66e to your computer and use it in GitHub Desktop.
UnrealEngine 4: dynamic load UMG from c++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Fill out your copyright notice in the Description page of Project Settings. | |
UCLASS() | |
class HOPETOWERDEFENSE_API AHopePlayerController : public APlayerController | |
{ | |
//GENERATED_BODY() | |
GENERATED_UCLASS_BODY() | |
public: | |
//AHopePlayerController(const FObjectInitializer& ObjectInitializer); | |
virtual ~AHopePlayerController(); | |
public: | |
virtual void BeginPlay() override; | |
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = UI) | |
TSubclassOf<UGameWidget> WidgetClass; | |
UPROPERTY() | |
UGameWidget* WidgetInstance; | |
}; | |
AHopePlayerController::AHopePlayerController(const FObjectInitializer& ObjectInitializer) | |
: Super(ObjectInitializer) | |
{ | |
//Must put in constructor | |
ConstructorHelpers::FClassFinder<UGameWidget> PutNameHere(TEXT("/Game/MyUMG")); | |
if (PutNameHere.Class) { | |
WidgetClass = PutNameHere.Class; | |
} | |
} | |
void AHopePlayerController::BeginPlay() | |
{ | |
Super::BeginPlay(); | |
if (WidgetClass) { | |
if (!WidgetInstance) { | |
WidgetInstance = CreateWidget<UGameWidget>(this, WidgetClass); | |
UImage* image = NewObject<UImage>(UImage::StaticClass()); | |
image->SetVisibility(ESlateVisibility::Visible); | |
UPanelWidget* rootPanel = (UPanelWidget*)WidgetInstance->GetRootWidget(); | |
//UPanelWidget* rootPanel = (UPanelWidget*)WidgetInstance->GetWidgetFromName(TEXT("RootCanvasPanel")); | |
rootPanel->AddChild(image); | |
UCanvasPanelSlot* canvasPanelSlot = (UCanvasPanelSlot*)image->Slot; | |
auto slot = image->Slot; | |
canvasPanelSlot->SetPosition(FVector2D(100, 100)); | |
} | |
} | |
if (!WidgetInstance->GetIsVisible()) | |
{ | |
WidgetInstance->AddToViewport(); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment