In this lesson, you will learn how to pause your game while it’s running to inspect your C++ code line-by-line, allowing you to catch logic errors in real-time.
Attaching the Debugger
When you work with C++, you aren't just writing text files; you are creating instructions for your computer. If your game crashes or behaves unexpectedly, you need a way to "look under the hood."
- Ensure your project is open in both Unreal Engine and Visual Studio.
- In Visual Studio, ensure your configuration is set to DebugGame Editor.
- Go to the Debug menu at the top and select Attach to Process.
- Search for your project’s name (it will end in
-Win64-DebugGame.exe) and click Attach.
Once attached, your editor is now "linked" to your IDE. If your code hits an error, Visual Studio will take control, pause the engine, and show you exactly where the issue occurred.
Using Breakpoints
A breakpoint is a red dot you place in the margin of your code editor. It tells the computer, "Stop everything right here so I can look at what’s happening."
Imagine you have a function that calculates player health, but the math seems wrong:
void AMyCharacter::TakeDamage(float Amount)
{
Health -= Amount; // Place a breakpoint on this line!
UE_LOG(LogTemp, Warning, TEXT("Current Health: %f"), Health);
}
When you trigger TakeDamage in the editor, the game will freeze. Visual Studio will highlight that line in yellow. You can now hover your mouse over Health or Amount to see their current values in memory. If Amount is 500 when it should be 10, you’ve instantly found your bug.
Stepping Through Code
Once paused, use the "Step Over" (F10) button in Visual Studio to move to the next line of code. This allows you to follow the flow of logic step-by-step, verifying that your if statements and loops are executing exactly how you intended.
Key Takeaway: By attaching your debugger and using breakpoints, you turn hidden logic errors into visible, fixable mistakes.