Unreal Engine 5(UE5)에서 인터페이스를 상속하고 이를 구현하는 방법을 알아보겠습니다.
인터페이스는 클래스 간의 공통 기능을 정의하고, 이를 통해 코드의 유연성과 재사용성을 높일 수 있습니다.
1. 인터페이스 정의하기
먼저, 인터페이스 클래스를 정의합니다. 인터페이스는 UINTERFACE 매크로를 사용하여 정의합니다.
// MyInterface.h
#pragma once
UINTERFACE(MinimalAPI)
class UMyInterface : public UInterface
{
GENERATED_BODY()
};
class IMyInterface
{
GENERATED_BODY()
public:
virtual void MyFunction() = 0;
};
위 코드에서 UMyInterface는 인터페이스 클래스이고, IMyInterface는 이 인터페이스를 구현하는 클래스입니다. MyFunction은 순수 가상 함수로, 이를 구현하는 클래스에서 반드시 정의해야 합니다.
2. 인터페이스 구현하기
이제, 인터페이스를 구현하는 클래스를 생성합니다. 이 클래스는 AActor와 IMyInterface를 상속받습니다.
// MyActor.h
#pragma once
UCLASS()
class MYPROJECT_API AMyActor : public AActor, public IMyInterface
{
GENERATED_BODY()
public:
AMyActor();
virtual void MyFunction() override;
};
// MyActor.cpp
AMyActor::AMyActor()
{
PrimaryActorTick.bCanEverTick = true;
}
void AMyActor::MyFunction()
{
UE_LOG(LogTemp, Warning, TEXT("MyFunction called!"));
}
위 코드에서 AMyActor 클래스는 IMyInterface를 구현하며, MyFunction 함수를 정의합니다.
3. 인터페이스 구현 여부 확인하기
마지막으로, 객체가 특정 인터페이스를 구현하는지 확인하는 방법을 알아보겠습니다. 이를 위해 ImplementsInterface 함수를 사용합니다.
// SomeOtherClass.cpp
void ASomeOtherClass::CheckInterfaceImplementation(AActor* Actor)
{
if (Actor->GetClass()->ImplementsInterface(UMyInterface::StaticClass()))
{
IMyInterface* Interface = Cast<IMyInterface>(Actor);
if (Interface)
{
Interface->MyFunction();
}
}
else
{
UE_LOG(LogTemp, Warning, TEXT("Actor does not implement MyInterface"));
}
}
위 코드에서 CheckInterfaceImplementation 함수는 제공된 Actor가 UMyInterface를 구현하는지 확인합니다. 만약 액터가 인터페이스를 구현한다면, 이를 IMyInterface로 캐스팅하고 MyFunction을 호출합니다.
이와 같은 방법으로 UE5에서 인터페이스를 정의하고 구현하며, 이를 확인할 수 있습니다. 인터페이스를 사용하면 코드의 유연성과 재사용성을 높일 수 있어, 복잡한 프로젝트에서도 효율적으로 작업할 수 있습니다.
이 글이 도움이 되셨길 바랍니다! 추가로 궁금한 점이 있으면 언제든지 댓글로 남겨주세요.