利用C++扩展蓝图库函数

来源:互联网 发布:java权限控制框架 编辑:程序博客网 时间:2024/05/29 07:47

在UE4中蓝图本身已经非常强大,但是并没有强大到没有任何缺陷  --Mantra

如果你也遇到了上面的问题,可以继续往下看,我们接下来就会用C++扩展已有的蓝图功能。

首先需要创建一个特殊的C++类(需要继承自BlueprintFunctionLibrary),具体操作可以见下图


创建完成后会编译工程源码并且会自动打开VS(笔者用的是VS15),接下来我们编辑自定义功能。在做一个完整的功能之前最好先做测试,所以我们首先会写一个简单的函数来做测试(至于代码中出现的UFUNCTION之类的宏就不多做解释啦)

有几个点需要注意一下:

1)函数需要使用UFUNCTION进行修饰,否则蓝图无法调用

2)函数需要使用static修饰

3)一般定义成public,方便外部访问

案例一:测试函数

public:// 测试函数,主要用来测试UFUNCTION(BlueprintCallable, Category = "Mantra|Tool")static void GetCurrentActorInfo(AActor* Actor);
void UMyBlueprintFunctionLibrary::GetCurrentActorInfo(AActor* Actor){// 测试两种打印方式if (GEngine){GEngine->AddOnScreenDebugMessage(-1, 5, FColor::Blue, TEXT("Function Called"));}UE_LOG(LogTemp, Warning, TEXT("Called Function"));}

在蓝图中的效果


案例2:对一个数组进行随机排序

主要代码如下:

UFUNCTION(BlueprintPure, Category = "Mantra|Tool")static TArray<int32> RandomizeIntArray(const TArray<int32> InArray);UFUNCTION(BlueprintCallable, Category = "Mantra|Tool")static void PrintArrayElement(const TArray<int32> InArray);

TArray<int32> UMyBlueprintFunctionLibrary::RandomizeIntArray(const TArray<int32> InArray){TArray<int32> NewArray = InArray;int32 temp;float randomNumber;// 利用排序算法对数组进行排序操作for (int32 i = NewArray.Num(); i > 1; --i){randomNumber = FMath::RandRange(0, i - 1);temp = NewArray[FMath::FloorToInt(randomNumber)];NewArray[FMath::FloorToInt(randomNumber)] = NewArray[i - 1];NewArray[i - 1] = temp;}return NewArray;}void UMyBlueprintFunctionLibrary::PrintArrayElement(const TArray<int32> InArray){for (int32 i = 0; i < InArray.Num(); ++i){UE_LOG(LogTemp, Warning, TEXT("Current Number is %d"), InArray[i]);}}

主要功能已经完成,接下来测试

在关卡蓝图中创建Int类型的数组,之后调用我们写好的函数,可参见下图


运行效果如图


总结

我们今天只是写了一个随机排序,大家可以根据需要写出对数组的各种排序。