.h
DECLARE_DELEGATE_OneParam(FLoadingDelegate, float)
DECLARE_DYNAMIC_MULTICAST_DELEGATE(FFinishDelegate);
UCLASS()
class P_C_API AAsyncAcator : public AActor
{
GENERATED_BODY()
public:
// Sets default values for this actor's properties
AAsyncAcator();
protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
public:
// Called every frame
virtual void Tick(float DeltaTime) override;
public:
TSharedPtr<FStreamableHandle> StreamableHandle;
FLoadingDelegate Delegate;
//动态多播委托于蓝图中自定义加载完成后事件
UPROPERTY(BlueprintAssignable)
FFinishDelegate FinishDelegate;
//加载进度
UPROPERTY(BlueprintReadOnly)
float Progress;
public:
//异步加载资源
UFUNCTION(BlueprintCallable, Category = "AsyncLoadAsset")
void LoadAssetStart(const TArray<FSoftObjectPath> Paths);
//异步加载资源完成后调用的函数
void LoadedFinished();
///更新加载进度
void UpDateProgress(float ProgressValue);
//更新进度
void RefreshProgress(float value);
};
.CPP
#include "AsyncAcator.h"
#include "Engine/AssetManager.h"
// Sets default values
AAsyncAcator::AAsyncAcator()
{
// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
}
// Called when the game starts or when spawned
void AAsyncAcator::BeginPlay()
{
Super::BeginPlay();
//绑定加载进度数值
Delegate.BindUObject(this,&AAsyncAcator::RefreshProgress);
}
// Called every frame
void AAsyncAcator::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
if (StreamableHandle.IsValid())
{
if (StreamableHandle->IsActive())
{
UpDateProgress(StreamableHandle->GetProgress());
}
}
}
void AAsyncAcator::LoadAssetStart(TArray<FSoftObjectPath> Paths)
{
//创建异步加载
StreamableHandle=UAssetManager::GetStreamableManager().RequestAsyncLoad(Paths,
FStreamableDelegate::CreateUObject(this,&AAsyncAcator::LoadedFinished));
//初始化进度
Progress=0;
}
void AAsyncAcator::LoadedFinished()
{
// UKismetSystemLibrary::PrintString(this,TEXT("LoadedFinished!!"));
//完成后释放Handle
StreamableHandle->ReleaseHandle();
//执行完成后绑定
if (FinishDelegate.IsBound())
{
FinishDelegate.Broadcast();
}
}
void AAsyncAcator::UpDateProgress(float ProgressValue)
{
// UKismetSystemLibrary::PrintString(this,FString::SanitizeFloat(ProgressValue));
if (Delegate.IsBound())
{
Delegate.Execute(ProgressValue);
}
}
void AAsyncAcator::RefreshProgress(float value)
{
Progress=value;
}
用法:可派生蓝图类直接调用函数
cpp文件
链接:https://pan.baidu.com/s/1DJX3sZrpeTroaRC04-vdQQ
提取码:vqio
非插件 请自行修改.h class部分