1. 创建FNonAbandonableTask配合事件代理
DECLARE_DYNAMIC_DELEGATE_OneParam(FSwitchQGCJoystickDelegate, EJoystick, type);
class TaskExample : public FNonAbandonableTask
{
//定义需要的属性
/*Code*/
public:
FSwitchQGCJoystickDelegate SwitchJoystickDelegate;
EJoystick Type;
//构造函数,根据需要初始化数据
TaskExample(FSwitchQGCJoystickDelegate switchJoystickDelegate, EJoystick type = EJoystick::EJ_FengHuang)
{
this->SwitchJoystickDelegate = switchJoystickDelegate;
this->Type = type;
/*Code*/
}
FORCEINLINE TStatId GetStatId() const
{
RETURN_QUICK_DECLARE_CYCLE_STAT(TaskExample, STATGROUP_ThreadPoolAsyncTasks);
}
/*需要使用Task完成的任务*/
void DoWork()
{
/*Code*/
// 调用UI中的函数 必须主线程执行
AsyncTask(ENamedThreads::GameThread, [&]() {
/*Code*/
});
}
};
调用方式:
//(new FAutoDeleteAsyncTask<TaskExample>())->StartSynchronousTask();
方法2:使用UBlueprintAsyncActionBase
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "Kismet/BlueprintAsyncActionBase.h"
#include "AirsimPx4ConnectBPLibrary.h"
#include "SwitchQgcJoystick.generated.h"
extern enum class EJoystick :uint8;
/**
*
*/
UCLASS()
class AIRSIMPX4CONNECT_API USwitchQgcJoystick : public UBlueprintAsyncActionBase
{
GENERATED_BODY()
public:
DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FBPPin_Result, EJoystick, JoystickType);
/** 输出针脚1 */
UPROPERTY(BlueprintAssignable)
FBPPin_Result OnComplete;
EJoystick ActiveJoystickType;
public:
/** 蓝图节点:负责NewOBject 蓝图节点(创建工厂模式) */
UFUNCTION(BlueprintCallable, meta = (BlueprintInternalUseOnly = "true", WorldContext = "WorldContextObject", Category = "AirsimPx4Connect"))
static USwitchQgcJoystick* SwitchQgcJoystickAsync(UObject* WorldContextObject, EJoystick Type = EJoystick::EJ_FengHuang);
protected:
/** 程序通过(运行)节点是调用 */
virtual void Activate() override;
};
// Fill out your copyright notice in the Description page of Project Settings.
#include "SwitchQgcJoystick.h"
USwitchQgcJoystick* USwitchQgcJoystick::SwitchQgcJoystickAsync(UObject* WorldContextObject, EJoystick Type)
{
USwitchQgcJoystick* Ins = NewObject<USwitchQgcJoystick>();
Ins->ActiveJoystickType = Type;
return Ins;
}
void USwitchQgcJoystick::Activate()
{
//测试逻辑----开新线程,延迟一秒后随机调用成功或失败委托
Async(EAsyncExecution::ThreadPool, [&]()
{
FPlatformProcess::Sleep(1.0f);
// 该动作必须游戏线程中执行
AsyncTask(ENamedThreads::GameThread, [&]() {
this->OnComplete.Broadcast(this->ActiveJoystickType);
});
});
}
|