I’m fairly new to Unreal C++ and I have a bit of trouble finding how to correctly write a GetActorOfClass (singular, not GetAllActorsOfClass) in C++ in order to set a reference to another AActor at BeginPlay.
I have included GameplayStatics in the include in the header and cpp of AActor A and also the AActorB.h .
Now, what I did in the first place is simply in the AActor A header file, declare a UPROPERTY(EditAnywhere,BlueprintReadWrite) AActorB*ActorB so that I can set the AActor B manually in the editor but I would prefer to set it with a GetActorOfClass in the begin play of AActor A.
What would be the correct syntax for that ?
Thanks
Edit : This is the BP version of what I try to do in C++ :
Edit 2 : What I tried in C++
void ALocalMaster::BeginPlay()
{
Super::BeginPlay();
GameManager = static AActor*GetActorOfClass(const UObject*GameManager,TSubclassOf<AGameManager>);
}
Simple answer, just use GetAllActorOfClass
and dynamic cast it to your actor subtype if necessary:
// be sure to use #include "Containers/Array.h"
// as well as #include "Kismet/GameplayStatics.h"
// Assuming GameManager is of type AMyGameManagerActor*
void ALocalMaster::BeginPlay()
{
Super::BeginPlay();
AActor* FoundActor = UGameplayStatics::GetActorOfClass(GetWorld(),
AMyGameManagerActor::StaticClass());
GameManager = Cast<AMyGameManagerActor>(FoundActor);
if(GameManager == nullptr)
{
// handle error
}
else
{
// do stuff with GameManager
}
}