【转载】蓝图数组的通用排序方法

924 阅读1分钟

原文链接

我对原文格式进行了调整,并标注了关键重点

蓝图并没有为每一个类型的数组都提供排序方法,尤其是 自定义Actor ,但是,我们可以利用蓝图中的接口,通过 C++ 对蓝图数组进行排序。

首先,创建一个排序接口,ISort

// sort function for BP in UE4 by haisongliang
 
#pragma once
 
#include "CoreMinimal.h"
#include "UObject/Interface.h"
#include "Sort.generated.h"
 
// This class does not need to be modified.
UINTERFACE(MinimalAPI, BlueprintType)
class USort : public UInterface
{
	GENERATED_BODY()
};
 
/**
 * 
 */
class MYFUNCTIONLIBRARY_API ISort
{
	GENERATED_BODY()
 
	// Add interface functions to this class. This is the class that will be inherited to implement this interface.
public:
	
	UFUNCTION(BlueprintCallable, BlueprintImplementableEvent, Category = "System|Sort")
	bool smallerThan(const UObject* A);
};

然后,在函数库(或者其他 C++ 模块)中实现排序方法,

UCLASS()
class MYFUNCTIONLIBRARY_API UMyFunctionLibraryBPLibrary : public UBlueprintFunctionLibrary
{
	GENERATED_UCLASS_BODY()
 
	/*
	* sort objects with ISort interface.
	*/
	UFUNCTION(BlueprintCallable, Category = "System|Sort")
	static bool Sort(UPARAM(ref) TArray<UObject*>& array_to_sort, TArray<UObject*>& array_to_sort_ref);
};
bool UMyFunctionLibraryBPLibrary::Sort(UPARAM(ref) TArray<UObject*>& array_to_sort, TArray<UObject*>& array_to_sort_ref)
{
	bool success = true;
 
	for (size_t i = 0; i < array_to_sort.Num(); i++)
	{
		if (!array_to_sort[i] || !array_to_sort[i]->GetClass()->ImplementsInterface(USort::StaticClass())) ///< USort
		{
			success = false;
			break;
		}
	}
 
	if (!success)
	{
		return false;
	}
 
	array_to_sort.Sort([](const UObject& A, const UObject& B) {return ISort::Execute_smallerThan((UObject*)&A, &B); });
	array_to_sort_ref = array_to_sort;
	return true;
}

最后,在蓝图中对需要排序的数组的类型实现 ISort 接口即可。

原文链接

原版引擎里面是没这个功能的,不过官方商店提供了一个免费的插件,直接下载即可扩展功能,还是很方便的

插件名称就是 LE Extended Standard Library

image.png

应该还有其他的功能,不过暂时没想到其他要用的