【UE4 C++】 获取Actor、Controller、Pawn、Character

获取 Actor

TActorIterator 遍历

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

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

UKismetSystemLibrary::GetAllActorsOfClass

  • 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());
    }
    

UKismetSystemLibrary::GetAllActorsWithTag

  • Syntax

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

UKismetSystemLibrary::GetAllActorsWithInterface

  • Syntax

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

获取 Controller

可配合 Cast 转换成对应的 Controller

UKismetSystemLibrary::GetPlayerController

  • Syntax

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

    APlayerController* playerController = UGameplayStatics::GetPlayerController(GetWorld(), 0);
    

UWorld::GetFirstPlayerController

  • 代码实现

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

获取 Pawn

UKismetSystemLibrary::GetPlayerPawn

  • 代码实现

    APawn* myPawn = Cast<ADrone>(UGameplayStatics::GetPlayerPawn(GetWorld(), 0));
    

GetPawn

  • 代码实现

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

获取 Character

UGameplayStatics::GetPlayerCharacter

  • 代码实现

    ACharacter* myPawn = UGameplayStatics::GetPlayerCharacter(GetWorld(), 0);
    

GetCharacter

  • 代码实现

    ACharacter* myPawn = GetWorld()->GetFirstPlayerController()->GetCharacter();
    
posted @ 2021-05-07 22:51  砥才人  阅读(7218)  评论(0编辑  收藏  举报