WidgetC2.zip (372.9 KB)
Here is a working example. Toggle with space bar. All c++ only thing you need to set is the widget from the editor.
Implemented so that it mirrors your functions.
You have both enable and disable to see it in action. Calling enable if the blueprint widget is set to none will clear it from the screen and set it to none in the widget component.
Here is the main code
.h
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Character.h"
#include "MyCharacter.generated.h"
UCLASS()
class YOUR_API AMyCharacter : public ACharacter
{
GENERATED_BODY()
public:
AMyCharacter();
protected:
virtual void BeginPlay() override;
public:
virtual void Tick(float DeltaTime) override;
// Called to bind functionality to input
virtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override;
UPROPERTY(EditAnywhere,BlueprintReadWrite)
class UWidgetComponent* LockedOnWidget;
UPROPERTY(EditAnywhere, BlueprintReadWrite)
TSubclassOf<class UUserWidget> WidgetBPContainer;
UFUNCTION()
void EnableWidget();
UFUNCTION()
void DisableWidget();
void Toggle();
bool bToggle = true;
UPROPERTY();
UUserWidget* widgetInstance;
};
.cpp
#include "MyCharacter.h"
#include "Components/WidgetComponent.h"
AMyCharacter::AMyCharacter()
{
PrimaryActorTick.bCanEverTick = true;
LockedOnWidget = CreateDefaultSubobject<UWidgetComponent>(TEXT("LockedOnWidget"));
LockedOnWidget->SetupAttachment(GetRootComponent());
LockedOnWidget->SetWidgetSpace(EWidgetSpace::Screen);
}
void AMyCharacter::BeginPlay()
{
Super::BeginPlay();
}
// Called every frame
void AMyCharacter::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
}
void AMyCharacter::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)
{
Super::SetupPlayerInputComponent(PlayerInputComponent);
check(PlayerInputComponent);
PlayerInputComponent->BindAction("Toggle", IE_Pressed, this, &AMyCharacter::Toggle);
}
void AMyCharacter::EnableWidget() {
if (WidgetBPContainer != nullptr) {
widgetInstance = CreateWidget<UUserWidget>(GetWorld(), WidgetBPContainer);
LockedOnWidget->SetWidget(widgetInstance);
} else {
LockedOnWidget->SetWidget(nullptr);
if (widgetInstance != nullptr) {
widgetInstance->RemoveFromParent();
}
}
}
void AMyCharacter::DisableWidget() {
LockedOnWidget->SetWidget(nullptr);
if (widgetInstance != nullptr) {
widgetInstance->RemoveFromParent();
}
}
void AMyCharacter::Toggle() {
if (bToggle == true) {
EnableWidget();
}
else {
DisableWidget();
}
bToggle = !bToggle;
}
Spacebar toggles the widget through key binds