GetAllActorsOfClass with type

I’m trying to make a function that get’s all actors of a certain class. But I do not want it to return a TArray of Actors. I want it to return the actual TArray-type that I searched for. I would like to write:

TArray<AMyControllers> AllControllers = ULib::GetAllActorsOfClass<AMyControllers>(this);

This is as far as I got:

// TODO: below function does not work. Also TArray<Type*> FoundActors; must be TArray<AActor*> FoundActors; as well as the return-type... But I do not want that...
template <typename Type>
TArray<Type*> ULib::GetAllActorsOfClass(UObject* WorldContextObject)
{
	TArray<Type*> FoundActors;
	UGameplayStatics::GetAllActorsOfClass(WorldContextObject, Type, FoundActors); // Error <<< Type-parameter
	return FoundActors;
}

Did you try to provide Type’s static class ? Like Type::StaticClass()

UGameplayStatics::GetAllActorsOfClass(WorldContextObject, Type::StaticClass(), FoundActors);

That got rid of that error. Now it just requires an efficient way of converting all those AActor to Type. But I’m not even sure if using UGameplayStatics::GetAllActorsOfClass() is efficient if I then have to loop them all and convert them one by one to Type afterwards. What’s the most efficient way of returning the actual Type instead of AACtor?

Should I just create my own iterator (A new, community-hosted Unreal Engine Wiki - Announcements - Unreal Engine ForumsObject%26_Actor_Iterators,_Optional_Class_Scope_For_Faster_Search) instead of using UGameplayStatics?

template <typename Type>
TArray<Type*> ULib::GetAllActorsOfClass(UObject* WorldContextObject)
{
	TArray<AActor*> FoundActors;
	UGameplayStatics::GetAllActorsOfClass(WorldContextObject, Type::StaticClass(), FoundActors);
	// TODO: how to convert FoundActors to Type? is UGameplayStatics::GetAllActorsOfClass() even viable if we need to manually convert them all?
	return FoundActors;
}

Oh I see your point. So yes… I think you don’t have any other solution than casting your AActors to Type then. At least you know that they are all subclassed as Type otherwise providing a specific class to GetAllActorsOfClass wouldn’t make any sense. A static_cast would work and doesn’t affect performance that much, except the extra loop over FoundActors.

An other solution would be to use an actorIterator.

     template <typename Type>
     TArray<Type*> ULib::GetAllActorsOfClass(UWorld* World)
     {
         TArray<Type*> res;
         for(TActorIterator<Type> it(World); it; ++it)
         {
            res.Add(*it);
         }
         return res;
     }