Zurück zu Skills
gamedev-skills/awesome-gamedev-agent-skillsPrüfung bestanden

SKILL DETAIL

unreal-cpp-gameplay

gamedev-skills/awesome-gamedev-agent-skills/unreal-cpp-gameplay

Write Unreal Engine 5 C++ gameplay code: the UCLASS/UPROPERTY/UFUNCTION reflection macros, the Gameplay Framework (GameMode, Pawn, Character, PlayerController, Actor components), and the module Build.cs. Use when writing or debugging UE C++, deriving from AActor/ACharacter/ AGameModeBase, exposing properties to the editor or Blueprints, or when the user mentions Unreal C++, UCLASS, GENERATED_BODY, GameMode, ACharacter, or .Build.cs.

Installationen · 243Quelle ansehen

Installation

npx skills add https://github.com/gamedev-skills/awesome-gamedev-agent-skills --skill unreal-cpp-gameplay

Skill-Dateien

SKILL.md

Zuletzt synchronisiert · 25.10.2026

references/components-and-gc.md›
# Components, garbage collection & replication primer (UE 5.8 C++)

Depth for `unreal-cpp-gameplay`. Verified against the Gameplay Framework docs and the UE5
C++ programming references. Covers component creation/attachment, the UPROPERTY/GC ownership
rules that trip up newcomers, and a minimal replication example.

## Creating and attaching components

Default subobjects are created in the constructor; runtime components use `NewObject` +
`RegisterComponent`.

```cpp
// In the constructor — built into the Class Default Object, editable in the Blueprint subclass.
ACharacterBase::ACharacterBase()
{
    SpringArm = CreateDefaultSubobject<USpringArmComponent>(TEXT("SpringArm"));
    SpringArm->SetupAttachment(RootComponent);          // attach to an existing component
    SpringArm->TargetArmLength = 300.f;

    Camera = CreateDefaultSubobject<UCameraComponent>(TEXT("Camera"));
    Camera->SetupAttachment(SpringArm);                 // socket chain: root -> arm -> camera
}
```

```cpp
// At runtime (e.g. add a component after spawn):
UAudioComponent* Audio = NewObject<UAudioComponent>(this);
Audio->RegisterComponent();                              // required, or it won't tick/render
Audio->AttachToComponent(RootComponent, FAttachmentTransformRules::KeepRelativeTransform);
```

- `CreateDefaultSubobject` is **only** valid in a constructor; using it later asserts.
- `SetupAttachment` is for constructor-time hierarchy; `AttachToComponent` is the runtime call.

## Garbage collection ownership (the #1 newcomer crash)

The UE garbage collector only keeps `UObject`s alive if it can reach them through a reflected
reference. A raw `UObject*` member that isn't a `UPROPERTY` is invisible to the GC and can be
collected, leaving a dangling pointer.

```cpp
UPROPERTY()                                  // GC sees it -> stays alive while this owner lives
TObjectPtr<UMyDataObject> Data;

UPROPERTY()
TArray<TObjectPtr<AActor>> Tracked;          // containers of UObjects also need UPROPERTY

UMyDataObject* Raw;                           // BUG: not tracked; may be GC'd -> crash
```

Rules:
- Every `UObject`/Actor pointer that must persist gets a `UPROPERTY` (use `TObjectPtr<T>` in
  UE5; raw pointers still compile but `TObjectPtr` adds access tracking in the editor).
- Plain C++ data (ints, FStrings, FVectors, USTRUCTs of POD) doesn't need this — it's owned by
  value.
- For a UObject you create that has no UPROPERTY owner (rare), `AddToRoot()` pins it and
  `RemoveFromRoot()` releases it — but prefer proper ownership.
- A plain C++ class (not a UObject) can't use `UPROPERTY`. Hold UObjects there with
  `TStrongObjectPtr<T>`, or derive from `FGCObject` and report them in `AddReferencedObjects`
  (it also requires `GetReferencerName`).
- For references that must *not* keep the target alive (a cached target actor, a listener),
  use `TWeakObjectPtr<T>` and check `IsValid()`/`Get()` before each use.

## USTRUCT and UENUM for reflected data

```cpp
UENUM(BlueprintType)
enum class EWeaponType : uint8 { Pistol, Rifle, Shotgun };

USTRUCT(BlueprintType)
struct FWeaponStats
{
    GENERATED_BODY()
    UPROPERTY(EditAnywhere, BlueprintReadWrite) int32 Damage = 10;
    UPROPERTY(EditAnywhere, BlueprintReadWrite) float FireRate = 0.25f;
};
```

`BlueprintType` makes the enum/struct usable as Blueprint variables.

## Minimal replication (multiplayer)

```cpp
// Header
UPROPERTY(ReplicatedUsing = OnRep_Health)
float Health = 100.f;

UFUNCTION()
void OnRep_Health();                          // client callback when Health replicates

// Source
#include "Net/UnrealNetwork.h"
void AMyActor::GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& Out) const
{
    Super::GetLifetimeReplicatedProps(Out);
    DOREPLIFETIME(AMyActor, Health);          // register the property for replication
}
```

- Set `bReplicates = true;` in the constructor for the actor to replicate at all.
- Server authority: gameplay changes happen on the server; clients receive replicated state and
  react in `OnRep_` callbacks.

## Gotchas

- `NewObject` without `RegisterComponent` gives a component that exists but never ticks or
  renders.
- Forgetting `#include "Net/UnrealNetwork.h"` breaks `DOREPLIFETIME`.
- `TObjectPtr` implicitly converts to the raw pointer for calls, so existing `->`/`.` usage is
  unchanged; the difference is GC visibility and editor tooling, not syntax at call sites.
SKILL.md›
---
name: unreal-cpp-gameplay
description: >
  Write Unreal Engine 5 C++ gameplay code: the UCLASS/UPROPERTY/UFUNCTION reflection macros,
  the Gameplay Framework (GameMode, Pawn, Character, PlayerController, Actor components), and
  the module Build.cs. Use when writing or debugging UE C++, deriving from AActor/ACharacter/
  AGameModeBase, exposing properties to the editor or Blueprints, or when the user mentions
  Unreal C++, UCLASS, GENERATED_BODY, GameMode, ACharacter, or .Build.cs.
---

# Unreal C++ Gameplay

Write correct UE5 gameplay C++: the reflection macros that connect C++ to the editor and
Blueprints, the Gameplay Framework class roles, and module dependencies. Targets **UE 5.8**.

## When to use

- Use when creating C++ gameplay classes (`AActor`, `APawn`, `ACharacter`, `AGameModeBase`,
  `UActorComponent`), exposing properties/functions with `UPROPERTY`/`UFUNCTION`, setting up a
  GameMode's default classes, or adding a module dependency in `*.Build.cs`.
- Use when the project has a `Source/` tree with `*.h`/`*.cpp` using `UCLASS`, and `*.Build.cs`.

**When *not* to use:** designer-facing visual logic → `unreal-blueprints`. Player input
binding details → `unreal-enhanced-input`. AI logic → `unreal-behavior-trees`. This skill owns
the C++ class/reflection foundation those build on.

## Core workflow

1. **Name with the right prefix.** `A` = Actor-derived, `U` = `UObject`/component-derived,
   `F` = plain struct, `E` = enum, `I` = interface. The prefix must match the base class.
2. **Declare the class with reflection macros.** `UCLASS()` above the class, `GENERATED_BODY()`
   as the first line in the body, and `#include "ClassName.generated.h"` as the **last**
   include in the header.
3. **Expose data with `UPROPERTY`** (editor/Blueprint visibility *and* garbage-collection
   tracking) and behaviour with `UFUNCTION` (`BlueprintCallable`, etc.).
4. **Create components in the constructor** with `CreateDefaultSubobject<T>(TEXT("Name"))` and
   set the `RootComponent`.
5. **Know the framework roles:** `AGameModeBase` sets the rules + default classes; `APawn`/
   `ACharacter` is the controllable body; `APlayerController` is the player's will;
   `UActorComponent` is reusable behaviour.
6. **Add module dependencies** to `*.Build.cs` (e.g. `EnhancedInput`) or unresolved-symbol
   link errors follow.
7. **Verify** by compiling (Live Coding `Ctrl+Alt+F11` from the editor, or a full build from
   the IDE with the editor closed) and checking the class/properties appear in the editor. For
   automation tests, run headless with
   `UnrealEditor-Cmd <Project>.uproject -ExecCmds="Automation RunTest MyGame;Quit"`
   (`RunTest` takes a test name, a dotted prefix, or `Group:<name>`).

## Patterns

### 1. Minimal Actor class (header + source)

```cpp
// Pickup.h
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "Pickup.generated.h"          // MUST be the last include

UCLASS()
class MYGAME_API APickup : public AActor   // MYGAME_API = your module's export macro
{
    GENERATED_BODY()
public:
    APickup();

    // EditAnywhere = tweak per-instance & on the CDO; BlueprintReadWrite = BP get/set.
    UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Pickup")
    int32 ScoreValue = 10;

    // UPROPERTY on a UObject* pointer is what keeps it from being garbage-collected.
    UPROPERTY(VisibleAnywhere)
    TObjectPtr<UStaticMeshComponent> Mesh;   // UE5: TObjectPtr instead of raw UStaticMeshComponent*

    UFUNCTION(BlueprintCallable, Category = "Pickup")
    void Collect();

protected:
    virtual void BeginPlay() override;
};
```

```cpp
// Pickup.cpp
#include "Pickup.h"
#include "Components/StaticMeshComponent.h"

APickup::APickup()
{
    Mesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("Mesh"));
    RootComponent = Mesh;                     // the mesh is this actor's root
}

void APickup::BeginPlay() { Super::BeginPlay(); }   // always call Super
void APickup::Collect()   { Destroy(); }
```

### 2. GameMode wiring its default classes

```cpp
// MyGameMode.cpp — set in the constructor so the engine spawns your classes.
AMyGameMode::AMyGameMode()
{
    DefaultPawnClass      = AMyCharacter::StaticClass();
    PlayerControllerClass = AMyPlayerController::StaticClass();
}
```

### 3. Module dependency in Build.cs

```csharp
// MyGame.Build.cs
PublicDependencyModuleNames.AddRange(new string[]
{
    "Core", "CoreUObject", "Engine", "InputCore", "EnhancedInput"
});
```

## Pitfalls

- **`generated.h` not last / missing** — compile errors like "Cannot find generated header" or
  "Expected an include". It must be the final include in the header.
- **Forgetting `GENERATED_BODY()`** — UHT (Unreal Header Tool) errors; it must be the first
  thing inside the class body.
- **Raw `UObject*` without `UPROPERTY`** — the garbage collector doesn't see it and may destroy
  it out from under you. Track every UObject pointer with `UPROPERTY` (use `TObjectPtr` in UE5).
- **Header/UPROPERTY edits with Live Coding** — function-body edits are reliable. Structural
  changes (new functions, new `UPROPERTY`s) rely on Object Reinstancing, which is on by default
  but less stable; code that caches pointers to reinstanced objects must refresh them. If the
  editor or Blueprints misbehave after such a change, close the editor and build from the IDE.
- **Wrong class prefix** — naming an Actor `UFoo` (or a component `AFoo`) breaks UHT; match the
  prefix to the base type.
- **Unresolved external symbol at link** — the module providing the API isn't in `Build.cs`
  `PublicDependencyModuleNames`.
- **Not calling `Super::`** in overridden `BeginPlay`/`Tick`/etc. skips engine setup.

## References

- For `UActorComponent` creation/attachment, the `UPROPERTY` garbage-collection ownership rules
  (`TObjectPtr`, `TArray<TObjectPtr<>>`, `TWeakObjectPtr`, holding UObjects from plain C++
  classes), and a replication primer, read
  `references/components-and-gc.md`.
- Primary docs: "Unreal Engine CPP Quick Start" and "Gameplay Framework"
  (`https://dev.epicgames.com/documentation/en-us/unreal-engine/gameplay-framework-in-unreal-engine`).

## Related skills

- `unreal-blueprints` — exposing C++ to designers; BP/C++ interop.
- `unreal-enhanced-input` — binding input in a C++ Pawn/Character.
- `unreal-behavior-trees` — C++ AI tasks driven from a behaviour tree.