Field Notes: C++ & the Engine
These are the lessons Unreal C++ programmers usually learn from a crash, a lost afternoon or a corrupted Blueprint. Each one is short; together they prevent most of the bugs that show up in Unreal code reviews.
1. Every UObject* member gets UPROPERTY()
A raw UObject* member is invisible to the garbage collector: the object can be collected while you still point at it, and the pointer isn't nulled. The crash comes "about once a minute", far from the cause. Write members as UPROPERTY() TObjectPtr<T>, use TWeakObjectPtr<T> for references that shouldn't keep the target alive, and FGCObject::AddReferencedObjects or TStrongObjectPtr in non-UObject classes. See Garbage Collection & TObjectPtr.
Applies to containers too: TArray<UObject*> without UPROPERTY() is as dangerous as a single pointer.
2. Header changes: close the editor and build
Live Coding patches function bodies. It can't reliably apply changes to reflected types (UPROPERTY, UFUNCTION, new members, class layout). After a header change: close the editor, build from the IDE, reopen. Never use the old Hot Reload path, and never save Blueprints after a reload that changed reflected types. Blueprints can silently lose variable values or references that way. When the editor says "modules are missing or built with a different engine version", build in the IDE first to see the real compile error.
3. IsValid() is not a null check
if (Actor) is true for an actor that was destroyed this frame and is waiting for garbage collection. IsValid(Actor) also checks that it isn't being destroyed or marked as garbage. Use IsValid for anything that can be destroyed: actors, components, objects whose owner can die. A plain null check is fine for things you created and own (a UDataAsset you loaded, a subsystem). The classic symptom of using the wrong one: a dead enemy that "dies" again, awarding double score.
4. The constructor runs for the CDO: keep it to defaults
The constructor runs once for the Class Default Object at engine start, again for each Blueprint subclass's archetype, and for every instance. So in a constructor:
- ✔
CreateDefaultSubobject,SetupAttachment, setting default values and tick settings. - ✘
GetWorld(), spawning, finding other actors, binding to other objects' delegates, timers, reading game state,LoadObjectof gameplay assets (useConstructorHelpers::FObjectFinderonly if you must, and preferEditDefaultsOnlyproperties set in a Blueprint child).
Gameplay setup goes in BeginPlay (or PostInitializeComponents, PossessedBy, OnRep_*).
A subtler CDO rule: changing a default in C++ doesn't change values a Blueprint or level instance has overridden. Unreal saves objects as differences from their archetype, so instances that kept the default follow your change, and instances that were edited don't. The model shows it.
#include <iostream>
#include <map>
#include <optional>
#include <string>
// A saved object stores only the properties that differ from its archetype (delta serialization).
struct Archetype { std::map<std::string, double> Defaults; };
struct SavedInstance { std::string Name; std::map<std::string, double> Overrides; };
double Load(const Archetype& cdo, const SavedInstance& s, const std::string& prop) {
auto it = s.Overrides.find(prop);
return it != s.Overrides.end() ? it->second : cdo.Defaults.at(prop);
}
int main() {
Archetype cdo{{{"MaxHealth", 100}, {"WalkSpeed", 500}}};
SavedInstance bpGrunt{"BP_Grunt", {}}; // never touched MaxHealth
SavedInstance bpBrute{"BP_Brute", {{"MaxHealth", 100}}}; // a designer typed 100 explicitly once,
// when another value was the default
SavedInstance placed{"BP_Grunt_C_3 (in L_Arena)", {{"WalkSpeed", 350}}};
for (int version : {1, 2}) {
if (version == 2) {
cdo.Defaults["MaxHealth"] = 150; // programmer changes the C++ default
cdo.Defaults["WalkSpeed"] = 600;
std::cout << "C++ defaults changed: MaxHealth 150, WalkSpeed 600\n";
}
for (const SavedInstance* s : {&bpGrunt, &bpBrute, &placed})
std::cout << " " << s->Name << ": MaxHealth " << Load(cdo, *s, "MaxHealth")
<< ", WalkSpeed " << Load(cdo, *s, "WalkSpeed") << "\n";
}
} BP_Grunt: MaxHealth 100, WalkSpeed 500
BP_Brute: MaxHealth 100, WalkSpeed 500
BP_Grunt_C_3 (in L_Arena): MaxHealth 100, WalkSpeed 350
C++ defaults changed: MaxHealth 150, WalkSpeed 600
BP_Grunt: MaxHealth 150, WalkSpeed 600
BP_Brute: MaxHealth 100, WalkSpeed 600
BP_Grunt_C_3 (in L_Arena): MaxHealth 150, WalkSpeed 350
BP_Brute stayed at 100 because its value is stored as an override, and the yellow "reset to default" arrow in the Details panel tells you so. After changing an important default, search for overrides (the Property Matrix or Reset to Default on many assets) instead of assuming everything follows.
5. Don't tick everything
Set PrimaryActorTick.bCanEverTick = false in every new actor and component unless it truly needs a per-frame update. For "every N seconds" use timers, for "when X happens" use delegates, and for cooldowns compare timestamps. When something must tick, set a TickInterval, and disable tick while idle. A level with 800 actors each ticking an empty Blueprint Event Tick costs measurable milliseconds for nothing. See Timers Instead of Tick.
6. Call Super, every time
Super::BeginPlay(), Super::Tick(DeltaSeconds), Super::EndPlay(Reason), Super::GetLifetimeReplicatedProps(Out), Super::PostInitializeComponents(), Super::SetupPlayerInputComponent(…). Missing one silently breaks Blueprint events, component registration or replication of the parent's properties. Linters and code review should flag overrides without a Super call.
7. Don't search the world every frame
UGameplayStatics::GetAllActorsOfClass and TActorIterator walk every actor. Fine once in BeginPlay; a real cost every tick. Cache results, or have actors register themselves with a manager (a UWorldSubsystem with a TArray<TWeakObjectPtr<AArenaEnemy>>) in BeginPlay and unregister in EndPlay.
8. Casting is cheap; hard references are not
Cast<AArenaCharacter>(Actor) is a fast class check in C++. In Blueprints, though, a Cast To BP_Boss node creates a hard reference to BP_Boss, so loading the Blueprint that contains it loads the boss, its meshes, sounds and textures. Cast to C++ base classes or interfaces in Blueprints, and keep asset-heavy Blueprints at the leaves of the reference graph. Check with the Size Map.
9. Renames need redirects
Renaming a C++ class, struct, property or enum that Blueprints or saved data use breaks those assets. Add a Core Redirect in DefaultEngine.ini so old saved names map to new ones:
[CoreRedirects]
+ClassRedirects=(OldName="/Script/Arena.ArenaHero",NewName="/Script/Arena.ArenaCharacter")
+PropertyRedirects=(OldName="/Script/Arena.ArenaCharacter.Hp",NewName="/Script/Arena.ArenaCharacter.Health")Similarly, moving assets in the Content Browser leaves redirectors behind; run Fix Up Redirectors on folders periodically, and commit the result in one change.
10. Wrap editor-only code
Code that uses editor modules (UnrealEd, asset tools) or editor-only data must be inside #if WITH_EDITOR (or live in an Editor module), and editor-only properties inside #if WITH_EDITORONLY_DATA. Otherwise the editor build works and the packaged build fails to compile, typically on the day of a deadline.
Test yourself
A C++ default for MaxHealth changes from 100 to 150. Which Blueprint keeps 100?
- Every Blueprint
- Blueprints that stored an explicit override for MaxHealth
- None
- Only placed instances
Why is GetAllActorsOfClass in Tick a problem?
- It is Blueprint-only
- It iterates every actor in the world every frame
- It returns destroyed actors
- It disables replication
What does a Core Redirect in DefaultEngine.ini do?
- Redirects network traffic
- Maps old class/property names in saved data to renamed ones
- Moves assets on disk
- Speeds up loading