【UE4】异步加载关卡 LoadingScreen ( 蓝图和C++ )
阅读原文时间:2023年07月11日阅读:2
  • 一般先跳转到一个临时的关卡,然后异步加载目标关卡,同时展示Loading界面
  • 对于含有流关卡的目标关卡,可以先载入子关卡

蓝图异步加载

  • 无进度条

C++ 异步加载关卡

bool bIsLoaded;

UPROPERTY()
    FString LoadPackagePath;

// 用于加载完成的回调
DECLARE_DYNAMIC_DELEGATE(FOnAsyncLoadFinished);

UFUNCTION(BlueprintCallable)
    void MyAsyncLoad(const FOnAsyncLoadFinished& OnAsyncLoadFinished);

UFUNCTION(BlueprintCallable)
    float GetLoadProgress();


//开始异步加载
void ALoadActor::MyAsyncLoad(const FOnAsyncLoadFinished& OnAsyncLoadFinished)
{
//不使用GetBaseFilename,编译 error C4458: LoadPackageAsync failed to begin to load a package···
    LoadPackagePath = FPaths::GetBaseFilename(LoadPackageSoftObjectPath.ToString(), false);

    bIsLoaded = false;

    UE_LOG(LogTemp, Warning, TEXT("String: %s"), *LoadPackagePath);
    LoadPackageAsync(
        LoadPackagePath,
        FLoadPackageAsyncDelegate::CreateLambda([=](const FName& PackageName, UPackage* LoadedPackage, EAsyncLoadingResult::Type Result)
            {
                if (Result == EAsyncLoadingResult::Failed)
                {
                    UE_LOG(LogTemp, Warning, TEXT("Load Failed"));
                }
                else if (Result == EAsyncLoadingResult::Succeeded)
                {
                    bIsLoaded = true;
                    UE_LOG(LogTemp, Warning, TEXT("Load Succeeded"));
                    OnAsyncLoadFinished.ExecuteIfBound();
                }
            }), 0, PKG_ContainsMap);
}

//获取加载的进度 -1 —— 100
float ALoadActor::GetLoadProgress()
{
    float FloatPercentage = GetAsyncLoadPercentage(*LoadPackagePath);
    if (!bIsLoaded)
    {
        FString ResultStr = FString::Printf(TEXT("Percentage: %f"), FloatPercentage);
        GEngine->AddOnScreenDebugMessage(-1, 2.0f, FColor::Green, ResultStr);
        UE_LOG(LogTemp, Warning, TEXT("Percentage: %f"), FloatPercentage);
    }
    else {
        FloatPercentage = 100;
    }
    return FloatPercentage;
}

效果

  • 获取依赖项
  • 将依赖项转为 FSoftObjectPath 存储到容器中
  • 使用 RequestAsyncLoad 加载
  • 使用 GetLoadCount 获取加载进度

参考部分代码

参考