【UE4 C++】 获取Actor、Controller、Pawn、Character
阅读原文时间:2023年07月11日阅读:2

获取 Actor

  • 可以用于遍历 Actor,也可以用于遍历 Component

    for (TActorIterator<AStaticMeshActor> ActorIter(GetWorld()); ActorIter; ++ActorIter)
    {
        UKismetSystemLibrary::PrintString(GetWorld(), FString::Printf(TEXT("%s"), *ActorIter->GetName()));
    }
  • Syntax

    static void GetAllActorsOfClass(const UObject* WorldContextObject, TSubclassOf<AActor> ActorClass, TArray<AActor*>& OutActors);
  • 代码实现

    TArray<AActor*> OutActors;
    UGameplayStatics::GetAllActorsOfClass(GetWorld(), AStaticMeshActor::StaticClass(), OutActors);
    for (AActor* actor : OutActors)
    {
    UKismetSystemLibrary::PrintString(GetWorld(), actor->GetName());
    }
  • Syntax

    static void GetAllActorsWithTag(const UObject* WorldContextObject, FName Tag, TArray<AActor*>& OutActors);
  • Syntax

    static void GetAllActorsWithInterface(const UObject* WorldContextObject, TSubclassOf<UInterface> Interface, TArray<AActor*>& OutActors);

获取 Controller

可配合 Cast 转换成对应的 Controller

  • Syntax

    static class APlayerController* GetPlayerController(const UObject* WorldContextObject, int32 PlayerIndex);
  • 代码实现

    APlayerController* playerController = UGameplayStatics::GetPlayerController(GetWorld(), 0);
  • 代码实现

    APlayerController* playerController = GetWorld()->GetFirstPlayerController();

获取 Pawn

  • 代码实现

    APawn* myPawn = Cast<ADrone>(UGameplayStatics::GetPlayerPawn(GetWorld(), 0));
  • 代码实现

    APawn* myPawn = GetWorld()->GetFirstPlayerController()->GetPawn();

获取 Character

  • 代码实现

    ACharacter* myPawn = UGameplayStatics::GetPlayerCharacter(GetWorld(), 0);
  • 代码实现

    ACharacter* myPawn = GetWorld()->GetFirstPlayerController()->GetCharacter();

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器

你可能感兴趣的文章