Counting blueprint class instances from C++

I’d like to get a count of the number of enemies left in the level to display in the UI.

The way I’m trying to do that is with a call to UGameplayStatics::GetAllActorsOfClass() from inside a custom GameState class.

However, the actors I need to count are blueprints. It’s unclear to me how to make that blueprint class a recognizable type in C++ in order to pass it to this function. It’s looking for TSubclassOf<AActor> ActorClass, which implies the class needs to be a C++ class inheriting from AActor. Is that even posssible?

Must I rewrite my entire enemy class in C++ to get this working?
Would it be easier to just do the operation in blueprints and send the resulting integer to the UI widget, bypassing C++ entirely?
Is there a third option I haven’t considered?

You could just add an “enemy” tag to your enemy actors blueprints and use GetAllActorsWithTag instead, that way the child class is irrelevant, since it seems you just want to count them.

Or something like this seems to work:

	TArray<AActor*> Actors;
	auto Path = FString("/Game/Experimental/PCG/NewBlueprint");
	const auto BpClass = ConstructorHelpersInternal::FindOrLoadClass(Path, AActor::StaticClass());
	UGameplayStatics::GetAllActorsOfClass(this, BpClass, Actors);
	UE_LOG(LogTemp, Warning, TEXT("Actor count %d"), Actors.Num());

This means any class inheriting from AActor. Both blueprint and c++ classes can be this. A playercontroller, pawn, character, gamemode, and so on are all deriving from AActor.

Meaning, when you call UGameplayStatics::GetAllActorsOfClass using “Actor” as a class to search for, it will find spawned objects of all the above classes both c++ and blueprints. This function is used while playing the game and retrieves instances of classes, meaning it doesn’t count blueprint files but instances present in the world.

The TSubclassOf<AActor> type means “A class of AActor or any class deriving from AActor”.

More on deriving classes (class inheritance) in OOP:

Inheritance (object-oriented programming) - Wikipedia

For reasons unexplained, GetAllActorsOfClass didn’t work with either technique. It compiled and ran, but the function always returned an empty set.

Adding the tag and using GetAllActorsWithTag was easy, quick, and seems to work beautifully.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.