TExcelTAD
Home › Unreal Engine 5 with C++ › UObject, AActor & UActorComponent

UObject, AActor & UActorComponent

Three base classes carry almost all gameplay code in Unreal. Choosing the right one is the first design decision for every new class.

Class What it is Has a transform? Placed in a level? Ticks?
UObject the root of the object system: reflection, garbage collection, serialization no no no (unless you add it)
AActor a UObject that lives in a world: can be spawned, placed, replicated, destroyed through its root component yes optional
UActorComponent a reusable piece of behaviour attached to an actor no as part of an actor optional
USceneComponent a component with a transform and attachment (child of UActorComponent) yes as part of an actor optional
UPrimitiveComponent a scene component that renders and/or collides: meshes, shapes yes as part of an actor optional

Rules of thumb:

  • Something that exists in the world, can be spawned or destroyed, or replicates on its own: Actor.
  • A capability you want on several kinds of actors (health, inventory, interaction): ActorComponent.
  • A capability that needs a position (a muzzle point, a trigger volume, a camera boom): SceneComponent or a subclass.
  • Data and logic that doesn't live in the world (an item definition, a quest, a save game, a subsystem): UObject (or UDataAsset, USaveGame, a UGameInstanceSubsystem).

An actor built from components

An actor has no transform of its own: its position is the position of its root component. Other scene components attach to the root, forming a tree, much like a scene graph.

cpp
// ArenaPickup.h
#pragma once

#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "ArenaPickup.generated.h"

class USphereComponent;
class UStaticMeshComponent;
class URotatingMovementComponent;

UCLASS()
class ARENA_API AArenaPickup : public AActor
{
    GENERATED_BODY()

public:
    AArenaPickup();

protected:
    UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Components")
    TObjectPtr<USphereComponent> Trigger;

    UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Components")
    TObjectPtr<UStaticMeshComponent> Mesh;

    UPROPERTY(VisibleAnywhere, Category = "Components")
    TObjectPtr<URotatingMovementComponent> Spinner;   // not a scene component: no transform
};
cpp
// ArenaPickup.cpp
#include "ArenaPickup.h"
#include "Components/SphereComponent.h"
#include "Components/StaticMeshComponent.h"
#include "GameFramework/RotatingMovementComponent.h"

AArenaPickup::AArenaPickup()
{
    PrimaryActorTick.bCanEverTick = false;            // components do the work

    Trigger = CreateDefaultSubobject<USphereComponent>(TEXT("Trigger"));
    Trigger->InitSphereRadius(60.f);
    Trigger->SetCollisionProfileName(TEXT("OverlapAllDynamic"));
    RootComponent = Trigger;

    Mesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("Mesh"));
    Mesh->SetupAttachment(Trigger);
    Mesh->SetRelativeLocation(FVector(0.f, 0.f, 20.f));
    Mesh->SetCollisionEnabled(ECollisionEnabled::NoCollision);

    Spinner = CreateDefaultSubobject<URotatingMovementComponent>(TEXT("Spinner"));
    Spinner->RotationRate = FRotator(0.f, 90.f, 0.f);  // degrees per second around Z (yaw)
}

Points that trip people up:

  • CreateDefaultSubobject is only for constructors. At runtime, create components with NewObject<UMyComponent>(this) and then call RegisterComponent() (and AttachToComponent for scene components).
  • SetupAttachment is the constructor version of attaching. At runtime use AttachToComponent(Parent, FAttachmentTransformRules::KeepRelativeTransform).
  • The TEXT("Mesh") name must be unique within the actor. It is how Blueprint subclasses and saved levels find the component, so renaming it later breaks data.
  • Mark component pointers VisibleAnywhere, not EditAnywhere: you want the component's properties editable, not the pointer replaced.

Spawning and destroying

cpp
FActorSpawnParameters Params;
Params.Owner = this;
Params.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AdjustIfPossibleButAlwaysSpawn;

AArenaPickup* Pickup = GetWorld()->SpawnActor<AArenaPickup>(PickupClass, SpawnTransform, Params);

// later
Pickup->Destroy();          // marks it for destruction; EndPlay runs, memory is reclaimed by GC
Pickup->SetLifeSpan(5.f);   // or destroy itself after 5 seconds

PickupClass is usually a UPROPERTY(EditDefaultsOnly) TSubclassOf<AArenaPickup> PickupClass; so a designer can choose a Blueprint subclass with a different mesh.

A model: transforms through the attachment tree

A scene component's world location is its parent's world transform applied to its relative transform. This model keeps only location and yaw (rotation about Z, the up axis in Unreal) and walks the tree from the root.

cpp · try it yourself
#include <iostream>
#include <iomanip>
#include <cmath>
#include <string>
#include <vector>

struct SceneComponent {
    std::string Name;
    SceneComponent* Parent = nullptr;
    double RelX = 0, RelY = 0, RelZ = 0, RelYawDeg = 0;

    // World transform = parent's world transform applied to our relative one.
    void World(double& x, double& y, double& z, double& yaw) const {
        if (!Parent) { x = RelX; y = RelY; z = RelZ; yaw = RelYawDeg; return; }
        double px, py, pz, pyaw;
        Parent->World(px, py, pz, pyaw);
        double r = pyaw * 3.14159265358979 / 180.0;
        x = px + RelX * std::cos(r) - RelY * std::sin(r);
        y = py + RelX * std::sin(r) + RelY * std::cos(r);
        z = pz + RelZ;
        yaw = pyaw + RelYawDeg;
    }
};

int main() {
    std::cout << std::fixed << std::setprecision(1);
    SceneComponent root{"Capsule (root)"};
    SceneComponent mesh{"Mesh", &root, 0, 0, -90};
    SceneComponent muzzle{"Muzzle", &mesh, 80, 0, 140};

    std::vector<SceneComponent*> parts = {&root, &mesh, &muzzle};
    for (double actorYaw : {0.0, 90.0}) {
        root.RelX = 1000; root.RelY = 500; root.RelZ = 90; root.RelYawDeg = actorYaw;
        std::cout << "actor at (1000, 500, 90), yaw " << actorYaw << "\n";
        for (auto* c : parts) {
            double x, y, z, yaw;
            c->World(x, y, z, yaw);
            std::cout << "  " << std::setw(15) << std::left << c->Name << std::right
                      << " (" << x << ", " << y << ", " << z << ")\n";
        }
    }
}
actor at (1000, 500, 90), yaw 0.0
  Capsule (root)  (1000.0, 500.0, 90.0)
  Mesh            (1000.0, 500.0, 0.0)
  Muzzle          (1080.0, 500.0, 140.0)
actor at (1000, 500, 90), yaw 90.0
  Capsule (root)  (1000.0, 500.0, 90.0)
  Mesh            (1000.0, 500.0, 0.0)
  Muzzle          (1000.0, 580.0, 140.0)

Turning the actor turns the muzzle with it, because the muzzle's offset is expressed in its parent's space. In UE you ask for the result with Muzzle->GetComponentLocation() and GetComponentRotation(), and for the actor's forward direction with GetActorForwardVector(), which is +X in Unreal.

Test yourself

Where does an actor's location come from?

  1. A member variable on AActor
  2. Its root component's transform
  3. The level file
  4. The GameMode

You need to add a component to an actor at runtime, after it was spawned. What do you use?

  1. CreateDefaultSubobject
  2. NewObject followed by RegisterComponent
  3. SpawnActor
  4. SetupAttachment

Health logic should be shared by players, enemies and destructible crates. What fits best?

  1. A base Actor class all three inherit
  2. A UActorComponent added to each
  3. Code in the GameMode
  4. A UObject stored in a global