Let’s say the class of the actor you want to find is ADoor (this will work perfectly if you substitute it for your own class.)
First, you need to include GameplayStatics in you cpp file:
#include "Kismet/GameplayStatics.h"
##Example of GetActorOfClass
ASomeActor is just whatever actor you need it to be.
//cpp file
void ASomeActor::BeginPlay() {
Super::BeginPlay();
ADoor* Door = UGameplayStatics::GetActorOfClass((), ADoor::StaticClass());
// Door is now a pointer to one of the ADoor objects in the world
}
##Example of GetAllActorsOfClass
// header file, in class definition
UPROPERTY() // Put this in the header file so you can mark it as UPROPERTY
TArray<AActor*> DoorsAsActors; // Without UPROPERTY, strange things may happen with garbage collection on TArray
// cpp file
void ASomeActor::BeginPlay() {
Super::BeginPlay();
UGameplayStatics::GetAllActorsOfClass((), ADoor::StaticClass(), DoorsAsActors);
for (AActor* DoorAsActor : DoorsAsActors) {
ADoor* Door = Cast<ADoor>(DoorAsActor);
// Now it is looping through all ADoor actors in world, with Door as the reference.
}
}
*First, we store the pointers to the ADoors in DoorsAsActors, cast to Actors, because GetAllActorsOfClass only works with arrays of Actors. *
Additional Notes
- Don’t put GetActorOfClass or GetActorsOfClass unconditionally in Tick (don’t run them every frame) because they are expensive. Instead, just declare the pointer in the class definition in the header file, and set the pointer in BeginPlay
- Don’t put them in the Constructor, use BeginPlay instead.
Hope this helps!