AActor class in Unreal Engine

Published on

Actor is the base class for an Object that can be placed or spawned in a level. It has visual representation and many useful functions defined. How to use it?

Platforma
AActor:
  • Can be placed in the world
  • Can have a visual representation (Mesh, ...)
  • Has function for spawning to the world
  • Has functions for processing movement
  • All classes inherited from AActor has an A prefix at the start of class name

Inheritance Hierarchy

Spawn an Actor into the Scene (Level)

Spawn an Actor (and any its inherited class) to the world in runtime

There's a template TSubclassOf<ClassType> that allows to store a variable that represents a class of a UClass type (and all its derived classes). UClass has built in functionality that allows reflection to work between C++ and Blueprint.

Class information from TSubclassOf is then used as the parameter for UWorld::SpawnActor, respectively with its template SpawnActor<Type>(UClass*, Location, Rotation) that actually spawn actors to the world in runtime.

<a href="/unreal-engine/uproperty">UPROPERTY</a>(EditDefaultsOnly)
TSubclassOf&lt;<a href="/unreal-engine/forward-declaration">class ASpawnedObjectClass</a>&gt; SpawnedObjectClass;

Of course, the class reference can be made right in the C++ class without the need to use Blueprint derived class, just refer to something like auto SpawnedObjectClass = ASpawnedObjectClass::StaticClass(); in such case.

Attach an actor into another actor

By spawning an actor into the world, regardless by what class it's being processed in the runtime, the actor acts independently based on own configuration. If the actor represents e.g. a tool, that should be tide to another AActor, e.g. ACharacter, the "Tool" AActor must be attached into its parent Actor, e.g. ACharacter.

Attaching to Meshes via Sockets

How to attach e.g. "Screwdriver" AActor into a hand of ACharacter?

If the "Screwdriver" or any other tool or even a gun or so (It really doesn't matter what kind of tool it is) is the part of the Skeleton, there's necessary to hide it first. It will be later replaced by the AActor for tools, for which actually we need to define a point where the tool actor has to be attached. This can be done through a socket. Socket is a pointer into which any Actor can be plugged. On Skeleton, the socket can be placed by clicking at a bone by right mouse button and selecting Add socket. If we hide some tool, because it's already a part of the Skeleton, we can add the socket as a child of the bone (tool) that we hid. If we did not, we must find an ideal location for placong the socket - probably a hand.

#include "Screwdriver.h"
void AExampleCharacter::BeginPlay()
{
    // Spawn the tool
    Screwdriver = GetWorld()-&gt;SpawnActor(AScrewdriver)(ScrewdriverClass);
    // Hide the tool that is part of the Skeleton
    GetMesh()-&gt;HideBoneByName(TEXT("Screwdriver_R"), EPhysBodyOp::PBO_None);
    // Attach Screwdriver into the socket point added to Skeleton
    Screwdriver-&gt;AttachToComponent(GetMesh(), FAttachmentTransformRules::KeepRelativeTransform, TEXT("SocketName"));
    Screwdriver-&gt;SetOwner(this);
}

Spawn an Actor (and any its inherited class) to the world in editor

As we work right in the editor, out of runtime, we use UBlueprintFunctionLibrary inherited class.

#if WITH_EDITOR
/**
 * <strong>Editor Only</strong> - Will not work in packaged build.
 *
 * <mark>Spawn an actor into a world</mark>
 *
 * @param ActorClassPath	Path of the actor class: "/Game/Folder/MyActor"
 * @param WorldPath			Path of the world: "/Game/Folder/MyWorld"
 * @param bUseEditorWorld	If true, will use the world currently open in the editor instead of the WorldPath
 * @param bOutSuccess		If the action was a success or not
 * @param OutInfoMsg		More information about the action's result
 *
 * @return The spawned actor
 */
UFUNCTION(BlueprintCallable, Category = "<a href="https://www.youtube.com/watch?v=7yP5C_LOYcU" target="_blank">Spawn Actors In World</a>")
static AActor* SpawnActorInWorld(FString ActorClassPath, FString WorldPath, bool bUseEditorWorld, bool& bOutSuccess, FString& OutInfoMsg);
#endif

    Relative path to assets:

    • /Game/Path/To/Asset - access an asset in the Content folder of the game
    • /PluginName/Path/To/Asset - access an asset in the Content folder of selected plugin

Get All Actors Of Class Examples

Get the names of all actors in the current editor world

#include "Kismet/BlueprintFunctionLibrary.h" // Engine
/**
 * <mark>Get the names of all actors in the current editor world</mark>
 *
 * @param bUseGameplayStatics	If want to use the function from GameplayStatics
 * @param bOutSuccess			If the action was a success or not
 * @param OutInfoMsg			More information about the action's result
 * 
 * @return Names of all the actors
 */
UFUNCTION(BlueprintCallable, Category = "<a href="https://www.youtube.com/watch?v=UOqRalVZEfw" target="_blank" rel="nofollow noopener">Alex Quevillon - Get All Actors Of Class</a>")
<strong>static TArray&lt;FString&gt; GetNamesOfAllActors(bool bUseGameplayStatics, bool& bOutSuccess, FString& OutInfoMsg);</strong>

Get the Mesh names of all static mesh actors in the current editor world

#include "Kismet/BlueprintFunctionLibrary.h" // Engine
/**
 * <mark>Get the Mesh names of all static mesh actors in the current editor world</mark>
 *
 * @param bUseGameplayStatics	If want to use the function from GameplayStatics
 * @param bOutSuccess			If the action was a success or not
 * @param OutInfoMsg		More information about the action's result
 *
 * @return Names of all the actors
 */
UFUNCTION(BlueprintCallable, Category = "<a href="https://www.youtube.com/watch?v=UOqRalVZEfw" target="_blank" rel="nofollow noopener">Alex Quevillon - Get All Actors Of Class</a>")
<strong>static TArray&lt;FString&gt; GetMeshNamesOfAllStaticMeshActors(bool bUseGameplayStatics, bool& bOutSuccess, FString& OutInfoMsg);</strong>

Iterating over all Actors in a given level

Functions below are usable for all Run-Time instances of actors. Iterators in Unreal Engine are always accurate. More info about Iterators in the Iterators handbook

It may be made with TActorRange class which is part of the "EngineUtils.h".

#include "EngineUtils.h"
#include "GameFramework/Controller.h"
void AExampleProject::EndGame(bool bIsPlayerWinner)
{
	// foor loop through every controller in the world
	for(AController* Controller : TActorRange&lt;AController&gt;(GetWorld()))
	{
		bool bIsWinner = Controller-&gt;IsPlayerController() == bIsPlayerWinner;
		Controller-&gt;GameHasEnded(Controller-&gt;GetPawn(), bIsWinner);
	}
}

Iterating over all AI characters to check whether there is still any alive. If not, end the game with Winner state..

// ExampleAIControlller.cpp
#include "ExampleCharacter.h"
bool AExampleAIController::IsDead() const
{
	AExampleCharacter* ControlledCharacter = Cast&lt;AExampleCharacter&gt;(GetPawn());
	if(ControlledCharacter != nullptr){
		return ControlledCharacter-&gt;IsDead();
	}

	return true;
}

// ExampleGameMode.cpp
#include "ExampleAIController.h"
void AExampleGameMode::PawnKilled(APawn* PawnKilled)
{
  Super::PawnKilled(PawnKilled);

  for(AExampleAIController* Controller : TActorRange&lt;AController&gt;(GetWorld()))
  {
    if(!Controller-&gt;IsDead()) return;
  }

  EndGame(true);
}

General Actor Iterator

void AYourControllerClass::PrintAllActorsLocations()
{
  //EngineUtils.h
  for (TActorIterator&lt;AActor&gt; ActorItr(GetWorld()); ActorItr; ++ActorItr )
  {
    ClientMessage(ActorItr-&gt;GetName());
    ClientMessage(ActorItr-&gt;GetActorLocation().ToString());
  }
}

On Hit trigger

 //.h file
<a href="/unreal-engine/uproperty">UPROPERTY</a>(VisibleAnywhere, Category = "Movement")
<a href="/unreal-engine/forward-declaration">class</a> UProjectileMovementComponent* ProjectileMC;
	
// .cpp file
#include "<a href="/unreal-engine/movement#UProjectileMovementComponent">GameFramework/ProjectileMovementComponent.h</a>"
AProjectile::BeginPlay()
{
    ProjectileMesh-&gt;OnComponentHit.AddDynamic(this, &AProjectile::OnHit); //Collision Presets must be Enabled (Query and Physics) for handling Hit events
}
void AProjectile::OnHit(<a href="unreal-engine/components#UPrimitiveComponent">UPrimitiveComponent</a>* HitComp, AActor* OtherActor, UPrimitiveComponent* OtherComp, FVector NormalImpulse, const FHitResult& Hit)
{
   if(!GetOwner() || OtherActor && OtherActor != this && OtherActor != GetOwner())
   {
      Destroy();
      return;
   }
   // <a href="/unreal-engine/classes/ugameplaystatics#apply-damage">Apply Damage</a>  
   // <a href="/unreal-engine/classes/ugameplaystatics#spawn">Spawn sound & particle effect</a>
   // <a href="/unreal-engine/classes/ugameplaystatics#play">Play Sound</a>
   Destroy();
}

Merge Actors With C++

The function below shows an example of merging all actors in a scene into a single merged actor.

Merge all actors in scene on click
#include "Kismet/BlueprintFunctionLibrary.h" // Engine
#if WITH_EDITOR
/**
 * <strong>Editor Only</strong> - Will not work in packaged build.
 * 
 * <mark>Merge Static Mesh Actors</mark>
 *
 * @param Actors			The actors to merge
 * @param DestinationPath	The path of the merged StaticMesh asset: "/Game/Folder/MyStaticMesh"
 * @param bOutSuccess		If the action was a success or not
 * @param OutInfoMsg		More information about the action's result
 * 
 * @return The merged StaticMesh
 */
UFUNCTION(BlueprintCallable, Category = "<a href="https://www.youtube.com/watch?v=G_5LOUT9i2k" target="_blank">Alex Quevillon - Merge actors</a>")
<strong>static class UStaticMesh* MergeActors(TArray&lt;class AStaticMeshActor*&gt; Actors, FString DestinationPath, bool& bOutSuccess, FString& OutInfoMsg);</strong>
#endif

Lock / unlock actor transform

#include "Kismet/BlueprintFunctionLibrary.h" // Engine
 /**
 * <mark>Lock or unlock an actor transform</mark>
 *
 * @param Actor					Actor to lock or unlock
 * @param bLockTransform		If true, will lock the transform. Otherwise unlock
 * @param bOutSuccess			If the action was a success or not
 * @param OutInfoMsg		More information about the action's result
 */
UFUNCTION(BlueprintCallable, Category = "<a href="https://www.youtube.com/watch?v=d5FxKIIP04g" target="_blank" rel="nofollow noopener">Alex Quevillon - Lock Actor And Level</a>")
<strong>static void LockActorTransform(AActor* Actor, bool bLockTransform, bool& bOutSuccess, FString& OutInfoMsg);</strong>
Vrealmatic consulting

Anything unclear?

Let us know!

Contact Us