Hi, I am new to programming in unreal. I have prior knowledge of c++ programming. I have a simple question, how to get reference to an actor in the world using c++. I know using
GetActorOfClass() and GetAllActorsOfClass() but i don’t know how to work with these functions to get the actor reference.
So help me to solve this problem. Example program is much appreciated.
There are many ways you can reference the actor in the world. How is this actor spawned? Is it placed in the level or do you spawn it from the code?
Thanks for your response. It is placed in level. But it is helpful to me in future if you provide me both with code example. Thanks
GetAllActorsOfClass is a Blueprint static function, if you want to get all actors of a specific class in C++ you should use TActorIterator, you can see an example in GameplayStatics.cpp under GetAllActorsOfClass function:
TSubclassOf<AActor> ActorClass;
TArray<AActor*> OutActors;
if (ActorClass)
{
for(TActorIterator<AActor> It((), ActorClass); It; ++It)
{
AActor* Actor = *It;
OutActors.Add(Actor);
}
}
You can place ActorClass and OutActors where you want, maybe in your header file with UPROPERTY macro to have them accessible from Blueprints or inside a function, it’s your choice!
Thanks a lot. But how do I get specific actor from the array. Also please give an example program for GetActorOfClass(). Thanks
It depends, what actor do you need? If you want to filter all actors by the display name you can edit the code as follows:
TSubclassOf<AActor> ActorClass;
TArray<AActor*> OutActors;
if (ActorClass)
{
for(TActorIterator<AActor> It((), ActorClass); It; ++It)
{
AActor* Actor = *It;
if(Actor->GetDisplayName == "MyActor")
{
OutActors.Add(Actor);
}
}
}
GetActorOfClass() returns the first actor found of a specific class instead of all actors, so if you have 2 actors in the world, it will return only the first found. If you want to call directly these functions from C++ instead of using TActorIterator you can #include “Kismet/GameplayStatics.h” and then call directly them like this:
TSubclassOf<AActor> ActorClass;
TArray<AActor*> OutActors;
UGameplayStatics::GetAllActorsOfClass((), ActorClass, OutActors);
Very much thanks for your reply. I understood well : ). Thanks
Sorry recently we had problems with moderation, it should be better now.