c5.Interface|接口
大约 2 分钟
接口组成
UINTERFACE:使用
UINTERFACE
宏声明的空UClass
,仅用于让反射系统识别接口,不包含具体逻辑。IInterface:以
I
开头的纯 C++ 类,包含所有纯虚函数声明,是真正需要被实现的接口。
接口声明
接口声明|BlueprintNativeEvent

#pragma once
#include "CoreMinimal.h"
#include "UObject/Interface.h"
#include "MyInterface.generated.h"
UINTERFACE(MinimalAPI)
class UMyInterface : public UInterface//继承自UInterface
{
GENERATED_BODY()
};
class MYPROJECT_API IMyInterface//使用时继承这个即可。
{
GENERATED_BODY()
public:
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category = "CameraInterface")
void IChangeCamera (int32 CameraID,float CameraSwitchTime) ;
};
接口声明|传统纯虚函数
#pragma once
#include "CoreMinimal.h"
#include "UObject/Interface.h"
#include "MyInterface.generated.h"
UINTERFACE(MinimalAPI)
class UMyInterface : public UInterface
{
GENERATED_BODY()
};
class MYPROJECT_API IMyInterface
{
GENERATED_BODY()
public:
void IChangeCamera (int32 CameraID,float CameraSwitchTime) = 0;//纯虚函数
};
接口实现
①.纯虚函数
MyClass.h
#pragma once
#include "CoreMinimal.h"
#include "MyInterface.h"
#include "MyClass.generated.h"
// 声明类并实现接口
UCLASS()
class MYPROJECT_API UMyClass : public UObject, public IMyInterface
{
GENERATED_BODY()
public:
//重写虚函数。
virtual void IChangeCamera override;
};
MyClass.cpp
#include "MyClass.h"
void UMyClass::MyMethod_Implementation()
{
// 实现接口方法的具体逻辑
}
②. BlueprintNativeEvent
MyClass.h
#pragma once
#include "CoreMinimal.h"
#include "MyInterface.h"
#include "MyClass.generated.h"
// 声明类并实现接口
UCLASS()
class MYPROJECT_API UMyClass : public UObject, public IMyInterface
{
GENERATED_BODY()
public:
void IChangeCamera_Implementation() override;
};
MyClass.cpp
#include "MyClass.h"
void UMyClass::MyMethod_Implementation()
{
// 实现接口方法的具体逻辑
}
接口调用
①.纯虚函数
IMenuInterface* Interface = Cast<IMenuInterface>(FocusActor);
if (Interface)
{
Interface->ISetLockVisibility(FocusActor,IsFocus);
}
②. BlueprintNativeEvent
IMenuInterface* Interface = Cast<IMenuInterface>(FocusActor);
if (Interface)
{
Interface->Execute_ISetLockVisibility(FocusActor,IsFocus);
}
if (Actor->Implements<UHighlightInterface>())
{
IHighlightInterface::Execute_UnHighlightActor(Actor);
}
蓝图接口
蓝图接口|声明定义


蓝图接口|实现


蓝图接口|调用
类内直接调用

类外需找到对象
