게임 개발/프로젝트

언리얼 C++ 클래스에 만들어둔 위젯 블루프린트 연동하기

이개 2026. 5. 13. 17:09

UserWidget 클래스를 생성한다.

 

만들어둔 위젯 블루프린트 이벤트그래프에서 파일->블루프린트 부모변경-> 만든 C++클래스를 선택한다.

 

코드로 델리게이트 바인딩하기

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

#pragma once

#include "CoreMinimal.h"
#include "Blueprint/UserWidget.h"
#include "LA_HUD.generated.h"

/**
 * 
 */
UCLASS()
class LASTARTEMIS_API ULA_HUD : public UUserWidget
{
	GENERATED_BODY()

public:

    // UMG 위젯이 화면에 “실제로 생성되고 붙을 때” 호출되는 C++ 초기화 함수
    virtual void NativeConstruct() override;


    //
    UFUNCTION(BlueprintImplementableEvent)
    void UpdateHP(float Current, float Max);

    void BindHealth();


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


#include "UI/LA_HUD.h"
#include "Kismet/GameplayStatics.h"
#include "GameFramework/Character.h"
#include "Character/Player/Component/LA_HealthComponent.h"
#include "UI/LA_HUD.h"

void ULA_HUD::NativeConstruct()
{
    Super::NativeConstruct();

    BindHealth();
}

void ULA_HUD::BindHealth()
{
    // OnHealthChanged에 UpdateHP 함수 바인딩
    ACharacter* PlayerCharacter =
        UGameplayStatics::GetPlayerCharacter(GetWorld(), 0);

    ULA_HealthComponent* HealthComp = PlayerCharacter->FindComponentByClass<ULA_HealthComponent>();

    if (HealthComp)
    {
        HealthComp->OnHealthChanged.AddDynamic(this, &ULA_HUD::UpdateHP);

        // 바인딩 직후 한번 실행해줌
        UpdateHP(HealthComp->GetCurrentHealth(), HealthComp->GetMaxHealth());
        UE_LOG(LogTemp, Log, TEXT("HUD: Binding & Initial Update Success!"));
    }
}