UE4接口
接口基础
接口 有两部分,一部分继承自UInterface,以U开头,一部分以I开头,用来写函数。
接口不允许定义使用UPROPERTY()宏标记的变量,普通变量可以。
使用GENERATED_BODY()宏
这个宏不能使用不带关键字的UFUNCTION()。
如果想实现UFUNCTION(),需要GENERATED_IINTERFACE_BODY()与GENERATED_UINTERFACE_BODY()。
注意需要实现一个带参构造,不需要声明。
代码是从引擎自带的模块里面截取的,方便借鉴。
UINTERFACE(Blueprintable, MinimalAPI)
class UBodyStateInputInterface : public UInterface
{
GENERATED_BODY()
};
class BODYSTATE_API IBodyStateInputInterface
{
GENERATED_BODY()
public:
/* Requests your device to update the skeleton. You can use this BS polling method or push updates to your skeleton*/
UFUNCTION(BlueprintNativeEvent, Category = "Body State Poll Interface")
void UpdateInput(int32 DeviceID, class UBodyStateSkeleton* Skeleton); //todo: define
};
UINTERFACE(meta = (CannotImplementInterfaceInBlueprint))
class ENGINE_API UControlRigInterface : public UInterface
{
GENERATED_UINTERFACE_BODY()
};
/** A producer of animated values */
class ENGINE_API IControlRigInterface
{
GENERATED_IINTERFACE_BODY()
public:
/**
* Perform any per tick setup work
*/
virtual void PreEvaluate_GameThread() = 0;
/**
* Perform any work that this control rig needs to do per-tick
*/
virtual void Evaluate_AnyThread() = 0;
/**
* Perform any per tick finalization work
*/
virtual void PostEvaluate_GameThread() = 0;
};
UFCInterface::UFCInterface(const class FObjectInitializer& ObjectInitializer) :Super(ObjectInitializer)
{
}
meta=(CannotImplementInterfaceInBlueprint)
带着个关键字,只能够接受UFUNCTION(BlueprintCallable)的方法,并且要写成虚函数
子类实现重写按照普通C++的方式重写。
不能够接受UFUNCTION(BlueprintCallable)的方法
可以接受
UFUNCTION(BlueprintNativeEvent, BlueprintCallable)
UFUNCTION(BlueprintImplementableEvent, BlueprintCallable)
UFUNCTION(BlueprintNativeEvent)
UFUNCTION(BlueprintImplementableEvent)
等方法,不需要写成虚函数
子类重写需要在.h和.cpp文件都加上_Implementation后缀
调用接口
BlueprintImplementableEvent 在蓝图实现,C++调用
BlueprintNativeEvent蓝图C++都可以实现,C++调用
BlueprintCallable 蓝图可调用
TArray<AActor*> ActorArray;
UGameplayStatics::GetAllActorsOfClass(GetWorld(), AInterActor::StaticClass(), ActorArray);
if (ActorArray.Num() > 0)
{
IMyInterface* ActPtr = Cast<IMyInterface>(ActorArray[0]);
ActPtr->Execute_TestFunc(ActorArray[0], FString("lele"));
}