蓝图数组的通用排序方法

蓝图并没有为每一个类型的数组都提供排序方法,尤其是自定义的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& array_to_sort, TArray& array_to_sort_ref);
};
bool UMyFunctionLibraryBPLibrary::Sort(UPARAM(ref) TArray& array_to_sort, TArray& 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()))
		{
			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接口即可。

你可能感兴趣的:(UnrealEngine4)