mirror of
https://github.com/sanjeed5/awesome-cursor-rules-mdc.git
synced 2026-11-30 14:52:55 +08:00
Regenerate all MDC rules with fresh Exa data and December 2025 best practices
- Refreshed all 241 library rules with current best practices - Updated Exa search results for all libraries with 2025 content - Fixed --regenerate-all flag logic to properly process all libraries - Removed duplicate astro entry in rules.json (merged tags) - Added missing docker.mdc and vim.mdc files - All rules now include modern patterns and anti-patterns - Updated with framework-specific recommendations for 2025 Technical improvements: - Fixed retry_failed_only logic in generate_mdc_files.py - Improved progress tracking for regeneration scenarios - Ensured proper handling of --refresh-exa flag
This commit is contained in:
+344
-300
@@ -1,363 +1,407 @@
|
||||
---
|
||||
description: Comprehensive best practices and coding standards for Unreal Engine projects. Covers code organization, performance, security, testing, and common pitfalls to ensure maintainable, efficient, and robust game development.
|
||||
globs: *.h,*.cpp,*.uasset,*.umap,*.ini
|
||||
description: Definitive guidelines for writing consistent, performant, and maintainable C++ and Blueprint code in Unreal Engine 5.x projects.
|
||||
globs: **/*
|
||||
---
|
||||
# Unreal Engine Best Practices and Coding Standards
|
||||
# unreal-engine Best Practices
|
||||
|
||||
This document outlines best practices and coding standards for Unreal Engine projects. Following these guidelines will help ensure maintainability, efficiency, and robustness.
|
||||
This guide outlines the essential coding standards and architectural patterns for developing robust and efficient Unreal Engine 5.x projects. Adhere to these rules to ensure high-quality, collaborative, and performant game development.
|
||||
|
||||
## 1. Code Organization and Structure
|
||||
## 1. Code Organization & Structure
|
||||
|
||||
### 1.1 Directory Structure
|
||||
### 1.1 Naming Conventions (C++)
|
||||
|
||||
* **`Source/`:** Contains all C++ source code.
|
||||
* **`[GameName]/`:** Root directory for your game's code.
|
||||
* **`Public/`:** Header files (.h) for classes and components.
|
||||
* **`Private/`:** Implementation files (.cpp).
|
||||
* **`[Feature]/`:** Subdirectories for specific game features (e.g., `Inventory`, `AI`, `UI`).
|
||||
* **`Core/`:** Classes and functions shared across the project.
|
||||
* **`UMG/`**: Code related to Unreal Motion Graphics (UI)
|
||||
* **`Content/`:** Contains all assets (meshes, textures, materials, blueprints, etc.).
|
||||
* **`[GameName]/`:** Root directory for your game's content.
|
||||
* **`Characters/`:** Character assets.
|
||||
* **`Environments/`:** Environment assets (meshes, textures, materials).
|
||||
* **`UI/`:** User interface assets.
|
||||
* **`Blueprints/`:** Blueprint classes and scripts.
|
||||
* **`Materials/`:** Material assets.
|
||||
* **`Textures/`:** Texture assets.
|
||||
* **`Audio/`:** Audio assets.
|
||||
* **`Animations/`:** Animation assets.
|
||||
* **`Config/`:** Configuration files (e.g., `DefaultGame.ini`, `DefaultEngine.ini`).
|
||||
* **`Plugins/`:** Plugin code and assets.
|
||||
Always follow Epic's and Splash Damage's C++ naming conventions for clarity and consistency.
|
||||
|
||||
### 1.2 File Naming Conventions
|
||||
* **Classes/Structs/Enums:** Use prefixes (`A`, `U`, `F`, `E`, `T`) followed by `PascalCase`.
|
||||
* **Member Variables:** Use `CamelCase`.
|
||||
* **Local Variables/Parameters:** Use `lower_snake_case`.
|
||||
* **Functions/Methods:** Use `PascalCase`.
|
||||
* **Boolean Variables:** Prefix with `b` (Epic) or `Is` (Verse-inspired).
|
||||
* **Event Handlers:** Prefix with `On`.
|
||||
* **Resource Creation/Destruction:** Use `Create`/`Destroy`.
|
||||
|
||||
* **C++ Classes:** Use descriptive names with prefixes indicating the class type.
|
||||
* `A[ClassName]` for Actors (e.g., `ACharacter`, `APlayerController`).
|
||||
* `U[ClassName]` for UObjects (e.g., `UInventoryComponent`, `UGameInstance`).
|
||||
* `F[StructName]` for Structs (e.g., `FHitResult`, `FVector`).
|
||||
* `E[EnumName]` for Enums (e.g., `EMovementMode`, `EInventoryItemType`).
|
||||
* `I[InterfaceName]` for Interfaces (e.g., `IInteractable`, `IUsable`).
|
||||
* **Blueprints:**
|
||||
* `BP_[AssetName]` (e.g., `BP_Character`, `BP_Door`).
|
||||
* **Assets:** Use descriptive names with prefixes indicating asset type.
|
||||
* `SM_[AssetName]` for Static Meshes (e.g., `SM_Table`, `SM_Chair`).
|
||||
* `T_[AssetName]` for Textures (e.g., `T_Ground_Albedo`, `T_Wall_Normal`).
|
||||
* `M_[AssetName]` for Materials (e.g., `M_Rock`, `M_Water`).
|
||||
* `MI_[AssetName]` for Material Instances (e.g., `MI_Rock_Dark`, `MI_Water_Shallow`).
|
||||
* `S_[AssetName]` for Sounds (e.g., `S_Explosion`, `S_Footstep`).
|
||||
* `Anim_[AssetName]` for Animations (e.g., `Anim_Run`, `Anim_Jump`).
|
||||
* `Mat_[AssetName]` for Matinee Sequences (Legacy Animation).
|
||||
* **Levels:**
|
||||
* `[LevelName]_Level` or `[LevelName]` (e.g., `MainMenu_Level`, `Gameplay`).
|
||||
❌ **BAD**
|
||||
```cpp
|
||||
// Class
|
||||
class my_actor_class : public AActor {};
|
||||
// Variable
|
||||
float playerHealth;
|
||||
// Function
|
||||
void get_player_name();
|
||||
// Enum
|
||||
enum E_WEAPON_TYPE { ... };
|
||||
// Boolean
|
||||
bool is_dead_player;
|
||||
```
|
||||
|
||||
### 1.3 Module Organization
|
||||
✅ **GOOD**
|
||||
```cpp
|
||||
// Class
|
||||
class AMyActorClass : public AActor {};
|
||||
// Variable
|
||||
float PlayerHealth; // Member variable
|
||||
float new_health_value; // Local variable/parameter
|
||||
// Function
|
||||
void GetPlayerName() const;
|
||||
// Enum
|
||||
enum EWeaponType : uint8 { EWeaponType_Sword, EWeaponType_Bow };
|
||||
// Boolean
|
||||
bool bIsDead; // or IsDead()
|
||||
// Event Handler
|
||||
void OnPlayerDied();
|
||||
// Resource Management
|
||||
UMyWidget* CreatePlayerHUD();
|
||||
void DestroyPlayerHUD(UMyWidget* WidgetToDestroy);
|
||||
```
|
||||
|
||||
* **Game Module:** The main module containing the game's core logic.
|
||||
* **Feature Modules:** Modules dedicated to specific game features (e.g., `InventoryModule`, `AIModule`).
|
||||
* **Plugin Modules:** Modules packaged as plugins, offering reusable functionality.
|
||||
### 1.2 Naming Conventions (Assets & Blueprints)
|
||||
|
||||
### 1.4 Component Architecture
|
||||
Prefix all assets and Blueprints with their type to aid discoverability and organization.
|
||||
|
||||
* **Favor Composition over Inheritance:** Use components to add functionality to actors.
|
||||
* **Create Reusable Components:** Design components to be generic and adaptable.
|
||||
* **Use Interfaces for Communication:** Define interfaces for components to interact with each other.
|
||||
* **Avoid God Components:** Break down complex functionality into smaller, more manageable components.
|
||||
* **Encapsulate Logic:** Keep component logic self-contained and avoid tight coupling.
|
||||
* **Blueprint Classes:** `BP_` (e.g., `BP_PlayerCharacter`)
|
||||
* **Materials:** `M_` (e.g., `M_Rock`)
|
||||
* **Material Instances:** `MI_` (e.g., `MI_Rock_Mossy`)
|
||||
* **Static Meshes:** `SM_` (e.g., `SM_Door`)
|
||||
* **Skeletal Meshes:** `SK_` (e.g., `SK_Character`)
|
||||
* **Textures:** `T_` (e.g., `T_Grass_D` for Diffuse, `T_Grass_N` for Normal)
|
||||
* **Particle Systems:** `P_` (e.g., `P_Explosion`)
|
||||
* **User Widgets:** `W_` (e.g., `W_MainMenu`)
|
||||
* **Gameplay Abilities:** `GA_` (e.g., `GA_Dash`)
|
||||
* **Gameplay Effects:** `GE_` (e.g., `GE_DamageOverTime`)
|
||||
* **Input Actions:** `IA_` (e.g., `IA_Jump`)
|
||||
|
||||
### 1.5 Code Splitting Strategies
|
||||
❌ **BAD**
|
||||
```
|
||||
Content/PlayerCharacter.uasset
|
||||
Content/RockMaterial.uasset
|
||||
Content/Explosion.uasset
|
||||
```
|
||||
|
||||
* **Feature-Based Splitting:** Organize code by game features.
|
||||
* **Module-Based Splitting:** Create separate modules for distinct functionalities.
|
||||
* **Async Loading:** Load assets and levels asynchronously to avoid hitches.
|
||||
* **Level Streaming:** Divide large levels into smaller, streamed sub-levels.
|
||||
* **Object Pooling:** Reuse frequently created and destroyed objects to reduce garbage collection.
|
||||
✅ **GOOD**
|
||||
```
|
||||
Content/MyGame/Characters/Player/BP_PlayerCharacter.uasset
|
||||
Content/MyGame/Environment/Materials/M_Rock.uasset
|
||||
Content/MyGame/FX/P_Explosion.uasset
|
||||
```
|
||||
|
||||
## 2. Common Patterns and Anti-patterns
|
||||
### 1.3 Folder Structure
|
||||
|
||||
### 2.1 Design Patterns
|
||||
Organize content by feature or domain, not by asset type. This improves project navigation and simplifies migration. Use `Developer-folder` for temporary, personal assets.
|
||||
|
||||
* **Singleton:** For classes with only one instance (e.g., `GameInstance`).
|
||||
* **Observer:** For event-driven communication between actors and components.
|
||||
* **Factory:** For creating objects without specifying their concrete classes.
|
||||
* **Command:** For encapsulating actions as objects, enabling undo/redo functionality.
|
||||
* **Strategy:** For defining a family of algorithms and making them interchangeable.
|
||||
* **Decorator:** For dynamically adding responsibilities to an object.
|
||||
* **Adapter:** For adapting the interface of a class to another interface clients expect.
|
||||
* **Object Pool:** Reuse objects to avoid frequent allocation and deallocation, especially useful for projectiles or particle effects.
|
||||
❌ **BAD**
|
||||
```
|
||||
Content/Materials/M_Rock.uasset
|
||||
Content/Blueprints/BP_PlayerCharacter.uasset
|
||||
Content/FX/P_Explosion.uasset
|
||||
```
|
||||
|
||||
### 2.2 Recommended Approaches for Common Tasks
|
||||
✅ **GOOD**
|
||||
```
|
||||
Content/MyGame/Environment/Props/Rock/M_Rock.uasset
|
||||
Content/MyGame/Characters/Player/BP_PlayerCharacter.uasset
|
||||
Content/MyGame/Weapons/Rifle/SK_Rifle.uasset
|
||||
Content/MyGame/Developer/MyName/BP_TestActor.uasset
|
||||
```
|
||||
|
||||
* **Actor Spawning:** Use `GetWorld()->SpawnActor<>()` to spawn actors dynamically.
|
||||
* **Input Handling:** Use Enhanced Input System for flexible and configurable input mappings.
|
||||
* **Timers:** Use `GetWorldTimerManager()` for timed events and actions.
|
||||
* **Collision Handling:** Use collision components and event delegates for collision detection.
|
||||
* **Networking:** Use Unreal Engine's built-in networking system for multiplayer games.
|
||||
* **Animation:** Leverage Animation Blueprints and State Machines for complex character animations.
|
||||
* **UI Design:** Utilize UMG (Unreal Motion Graphics) for creating dynamic user interfaces.
|
||||
### 1.4 C++ vs Blueprint Responsibility
|
||||
|
||||
### 2.3 Anti-patterns and Code Smells
|
||||
Delegate responsibilities based on performance and iteration needs.
|
||||
|
||||
* **God Classes/Actors:** Avoid overly large classes with too many responsibilities.
|
||||
* **Spaghetti Code:** Avoid complex and unstructured code that is difficult to understand and maintain.
|
||||
* **Magic Numbers:** Avoid hardcoded values without clear explanations.
|
||||
* **Copy-Pasted Code:** Refactor duplicated code into reusable functions or classes.
|
||||
* **Tight Coupling:** Minimize dependencies between classes and components.
|
||||
* **Memory Leaks:** Ensure proper memory management to avoid memory leaks.
|
||||
* **Excessive Casting:** Minimize the use of `Cast<>` as it can impact performance. Consider using interfaces or dynamic dispatch instead.
|
||||
* **Polling:** Avoid constantly checking for conditions; use events or delegates instead.
|
||||
* **Tick Abuse:** Avoid performing expensive operations in the `Tick()` function; use timers or asynchronous tasks.
|
||||
* **Not using the Actor Component System:** Neglecting to leverage components leads to monolithic, inflexible Actor classes.
|
||||
* **C++:** Implement performance-critical logic, complex algorithms, core systems (networking, AI pathfinding), and engine integrations.
|
||||
* **Blueprint:** Use for gameplay logic, data-driven iteration, UI, and visual scripting where performance is not paramount. Expose minimal, well-defined C++ functions and properties to Blueprint.
|
||||
|
||||
### 2.4 State Management
|
||||
❌ **BAD**
|
||||
```cpp
|
||||
// C++: Hardcoding specific gameplay rules that designers need to tweak frequently
|
||||
void AGameModeBase::BeginPlay()
|
||||
{
|
||||
Super::BeginPlay();
|
||||
// Complex hardcoded spawn logic
|
||||
SpawnEnemyAtLocation(FVector(0,0,0));
|
||||
}
|
||||
```
|
||||
```blueprint
|
||||
// Blueprint: Implementing a complex, frequently-called pathfinding algorithm
|
||||
// (This will be slow)
|
||||
```
|
||||
|
||||
* **Game Instance:** For storing global game state that persists across levels.
|
||||
* **Game Mode:** For managing game rules and player interactions within a level.
|
||||
* **Player State:** For storing player-specific information (e.g., score, inventory).
|
||||
* **Actor State:** For storing the state of individual actors (e.g., health, position).
|
||||
* **Use Data Assets:** For storing configurable game data (e.g., weapon stats, enemy parameters).
|
||||
* **State Tree:** For handling complex AI behavior.
|
||||
* **Gameplay Abilities:** For managing player abilities and interactions using the Gameplay Ability System (GAS).
|
||||
✅ **GOOD**
|
||||
```cpp
|
||||
// C++: Core system, exposed to Blueprint
|
||||
UCLASS()
|
||||
class MYGAME_API AEnemySpawner : public AActor
|
||||
{
|
||||
GENERATED_BODY()
|
||||
public:
|
||||
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Spawning")
|
||||
TSubclassOf<AEnemyCharacter> EnemyClassToSpawn;
|
||||
|
||||
### 2.5 Error Handling
|
||||
UFUNCTION(BlueprintCallable, Category = "Spawning")
|
||||
void SpawnEnemy(FVector Location);
|
||||
};
|
||||
```
|
||||
```blueprint
|
||||
// Blueprint: Data-driven iteration, using C++ core
|
||||
// In BP_GameMode
|
||||
// Event BeginPlay
|
||||
// -> Create Enemy Spawner (C++ class)
|
||||
// -> Set EnemyClassToSpawn (Blueprint-defined enemy BP)
|
||||
// -> Call SpawnEnemy (C++ function)
|
||||
```
|
||||
|
||||
* **Use `ensure()` for Debug Assertions:** Use `ensure()` to check for conditions that should always be true during development.
|
||||
* **Use `check()` for Critical Assertions:** Use `check()` for conditions that must be true in all builds.
|
||||
* **Use `try-catch` for Exception Handling:** Use `try-catch` blocks to handle exceptions in critical code sections.
|
||||
* **Log Errors and Warnings:** Use `UE_LOG()` to log errors and warnings for debugging and monitoring.
|
||||
* **Handle Potential Null Pointers:** Always check for null pointers before accessing object members.
|
||||
* **Implement Recovery Mechanisms:** Provide mechanisms to recover from errors gracefully (e.g., retry logic, fallback behavior).
|
||||
* **Validate Data:** Implement robust input and data validation to prevent unexpected errors.
|
||||
## 2. Common Patterns & Anti-patterns
|
||||
|
||||
### 2.1 Smart Pointers
|
||||
|
||||
Always use Unreal's smart pointers (`TSharedPtr`, `TWeakPtr`, `TUniquePtr`) for heap-allocated objects that do not derive from `UObject`. This prevents memory leaks and manages object lifetimes.
|
||||
|
||||
❌ **BAD**
|
||||
```cpp
|
||||
FMyClass* MyRawPtr = new FMyClass();
|
||||
// ... later, forgetting to delete
|
||||
delete MyRawPtr;
|
||||
```
|
||||
|
||||
✅ **GOOD**
|
||||
```cpp
|
||||
TSharedPtr<FMyClass> MySmartPtr = MakeShared<FMyClass>();
|
||||
// MySmartPtr will be automatically managed
|
||||
```
|
||||
|
||||
### 2.2 Const-Correctness
|
||||
|
||||
Mark functions and parameters `const` when they do not modify the object's state. This improves code safety and allows for better compiler optimizations.
|
||||
|
||||
❌ **BAD**
|
||||
```cpp
|
||||
// Function might accidentally modify state
|
||||
void GetPlayerName(FString& OutName);
|
||||
```
|
||||
|
||||
✅ **GOOD**
|
||||
```cpp
|
||||
// Clearly indicates no state modification
|
||||
FString GetPlayerName() const;
|
||||
// Parameter is read-only, no accidental modification
|
||||
void ProcessData(const FMyData& Data);
|
||||
```
|
||||
|
||||
### 2.3 `UFUNCTION` Specifiers
|
||||
|
||||
Use `BlueprintCallable` for functions that modify state or perform actions. Use `BlueprintPure` for functions that are getters and do not modify state. `BlueprintPure` functions appear as pure nodes in Blueprints.
|
||||
|
||||
❌ **BAD**
|
||||
```cpp
|
||||
UFUNCTION(BlueprintCallable)
|
||||
FString GetPlayerName(); // Should be pure if it doesn't modify state
|
||||
|
||||
UFUNCTION(BlueprintPure)
|
||||
void SetPlayerHealth(float NewHealth); // Should be callable as it modifies state
|
||||
```
|
||||
|
||||
✅ **GOOD**
|
||||
```cpp
|
||||
UFUNCTION(BlueprintPure, Category = "Player")
|
||||
FString GetPlayerName() const;
|
||||
|
||||
UFUNCTION(BlueprintCallable, Category = "Player")
|
||||
void SetPlayerHealth(float NewHealth);
|
||||
```
|
||||
|
||||
## 3. Performance Considerations
|
||||
|
||||
### 3.1 Optimization Techniques
|
||||
### 3.1 Avoid Heavy Logic in `Tick`
|
||||
|
||||
* **Profiling:** Use Unreal Engine's profiling tools (e.g., Unreal Insights, Stat commands) to identify performance bottlenecks.
|
||||
* **LODs (Level of Detail):** Use LODs to reduce the complexity of meshes at a distance.
|
||||
* **Occlusion Culling:** Use occlusion culling to hide objects that are not visible.
|
||||
* **Distance Culling:** Use distance culling to remove objects that are too far away.
|
||||
* **HLODs (Hierarchical Level of Detail):** Use HLODs to combine multiple static meshes into a single mesh.
|
||||
* **Instanced Static Meshes:** Use instanced static meshes to render multiple copies of the same mesh efficiently.
|
||||
* **Material Optimization:** Optimize material complexity to reduce pixel cost.
|
||||
* **Texture Optimization:** Use appropriate texture resolutions and compression formats.
|
||||
* **Blueprint Nativization:** Convert Blueprint logic to C++ for improved performance.
|
||||
* **Asynchronous Loading:** Load assets and levels asynchronously to avoid hitches.
|
||||
* **Object Pooling:** Reuse frequently created and destroyed objects to reduce garbage collection.
|
||||
* **Avoid Dynamic Allocation:** Minimize dynamic memory allocation during runtime.
|
||||
* **Optimize Collision:** Simplify collision geometry and disable unnecessary collision checks.
|
||||
* **Use Niagara:** Use the Niagara particle system for efficient particle effects.
|
||||
* **Implement Adaptive Resolution:** Dynamically adjust the resolution based on performance.
|
||||
* **Use GPU Profiling tools:** Tools like RenderDoc can help you debug what is happening on the GPU and pin point bottlenecks.
|
||||
The `Tick` function executes every frame. Move expensive operations to timers, async tasks, or event-driven logic to prevent performance bottlenecks.
|
||||
|
||||
### 3.2 Memory Management
|
||||
❌ **BAD**
|
||||
```cpp
|
||||
void AMyActor::Tick(float DeltaTime)
|
||||
{
|
||||
Super::Tick(DeltaTime);
|
||||
// Expensive raycast every single frame
|
||||
FHitResult Hit;
|
||||
GetWorld()->LineTraceSingleByChannel(Hit, Start, End, ECC_Visibility);
|
||||
// Complex AI calculations
|
||||
PerformComplexAIBehavior();
|
||||
}
|
||||
```
|
||||
|
||||
* **Use Smart Pointers:** Use `TSharedPtr` and `TWeakPtr` for automatic memory management.
|
||||
* **Avoid Circular Dependencies:** Prevent circular dependencies between smart pointers.
|
||||
* **Unload Unused Assets:** Unload assets that are no longer needed to free up memory.
|
||||
* **Garbage Collection:** Understand and optimize garbage collection behavior.
|
||||
* **Asset References:** Use asset references carefully to avoid unnecessary asset loading.
|
||||
* **Texture Streaming:** Use texture streaming to load only the necessary texture mipmaps.
|
||||
* **Minimize Asset Duplication:** Avoid creating duplicate assets; reuse existing ones whenever possible.
|
||||
* **Monitor Memory Usage:** Regularly monitor memory usage to identify potential leaks or excessive consumption.
|
||||
✅ **GOOD**
|
||||
```cpp
|
||||
void AMyActor::BeginPlay()
|
||||
{
|
||||
Super::BeginPlay();
|
||||
// Perform expensive operations periodically
|
||||
GetWorldTimerManager().SetTimer(MyTimerHandle, this, &AMyActor::PerformPeriodicCheck, 1.0f, true);
|
||||
}
|
||||
|
||||
### 3.3 Rendering Optimization
|
||||
void AMyActor::PerformPeriodicCheck()
|
||||
{
|
||||
FHitResult Hit;
|
||||
GetWorld()->LineTraceSingleByChannel(Hit, Start, End, ECC_Visibility);
|
||||
}
|
||||
|
||||
* **Minimize Draw Calls:** Reduce the number of unique meshes and materials.
|
||||
* **Optimize Shaders:** Simplify shader complexity to reduce rendering time.
|
||||
* **Use Post-Processing Effects Sparingly:** Post-processing effects can be expensive; use them judiciously.
|
||||
* **Optimize Lighting:** Use baked lighting whenever possible to reduce runtime lighting calculations.
|
||||
* **Shadow Optimization:** Optimize shadow settings to reduce shadow rendering cost.
|
||||
* **Use Mobile Rendering Features:** Utilize mobile rendering features for improved performance on mobile devices.
|
||||
* **Consider Nanite Carefully:** For next-gen fidelity, use Nanite, but be aware of its overhead on lower-end platforms.
|
||||
* **Virtual Shadow Maps:** Use virtual shadow maps to improve shadow quality and performance in large open worlds.
|
||||
// AI behavior triggered by events or specific conditions, not every frame
|
||||
void AMyActor::OnTargetDetected()
|
||||
{
|
||||
PerformComplexAIBehavior();
|
||||
}
|
||||
```
|
||||
|
||||
### 3.4 Package Size Optimization
|
||||
### 3.2 XR Optimization
|
||||
|
||||
* **Compress Assets:** Use asset compression to reduce package size.
|
||||
* **Remove Unused Assets:** Delete unused assets from the project.
|
||||
* **Texture Compression:** Use appropriate texture compression formats.
|
||||
* **Audio Compression:** Use appropriate audio compression formats.
|
||||
* **Blueprint Stripping:** Strip debug information from Blueprints in release builds.
|
||||
* **Cook Only Necessary Assets:** Ensure that only necessary assets are cooked for the target platform.
|
||||
* **Use Pak File Compression:** Employ compression when creating .pak files for deployment.
|
||||
For VR/AR/MR projects, follow Epic's XR Best Practices to ensure optimal performance and user comfort.
|
||||
|
||||
### 3.5 Lazy Loading
|
||||
* **Project Settings:** Start with the VR Template or `Scalable` quality, `Raytracing: Disabled`, `Starter Content: Disabled`. Enable `Forward Shading`, `MSAA`, `Instanced Stereo`, and `Mobile Multi-View` (for mobile VR).
|
||||
* **`.ini` Settings:** Set `vr.PixelDensity=1`, `r.SeparateTranslucency=0`, `r.HZBOcclusion=0` in `DefaultEngine.ini` under `[SystemSettings]`.
|
||||
* **Frame Rate:** Disable `Smooth Frame Rate` and `Use Fixed Frame Rate` in Project Settings > Engine > General Settings > Framerate.
|
||||
* **Nanite Foliage:** Utilize Nanite Foliage for dense, performant environments, especially for moving plants.
|
||||
|
||||
* **Stream Levels:** Load and unload levels dynamically based on player location.
|
||||
* **Load Assets On-Demand:** Load assets only when they are needed.
|
||||
* **Use Async Load Asset:** Use the `Async Load Asset` node in Blueprints or `LoadObjectAsync` in C++ to load assets asynchronously.
|
||||
* **Lazy Loading Proxies:** Create proxy objects that load the full asset only when accessed.
|
||||
* **Subobject loading:** Defer loading of certain UObject subobjects until needed.
|
||||
❌ **BAD**
|
||||
```ini
|
||||
// DefaultEngine.ini
|
||||
[SystemSettings]
|
||||
r.SeparateTranslucency=1 // Expensive for mobile VR
|
||||
r.HZBOcclusion=1 // Can be disabled for perf
|
||||
```
|
||||
|
||||
## 4. Security Best Practices
|
||||
✅ **GOOD**
|
||||
```ini
|
||||
// DefaultEngine.ini
|
||||
[SystemSettings]
|
||||
vr.PixelDensity=1
|
||||
r.SeparateTranslucency=0
|
||||
r.HZBOcclusion=0
|
||||
r.MotionBlurQuality=0
|
||||
r.PostProcessAAQuality=3
|
||||
r.BloomQuality=1
|
||||
r.EyeAdaptationQuality=0
|
||||
r.AmbientOcclusionLevels=0
|
||||
r.SSR.Quality=1
|
||||
r.DepthOfFieldQuality=0
|
||||
r.SceneColorFormat=2
|
||||
r.TranslucencyVolumeBlur=0
|
||||
r.TranslucencyLightingVolumeDim=4
|
||||
r.MaxAnisotropy=8
|
||||
r.LensFlareQuality=0
|
||||
r.SceneColorFringeQuality=0
|
||||
r.FastBlurThreshold=0
|
||||
r.SSR.MaxRoughness=0.1
|
||||
r.rhicmdbypass=0
|
||||
sg.EffectsQuality=2
|
||||
sg.PostProcessQuality=0
|
||||
```
|
||||
|
||||
### 4.1 Common Vulnerabilities
|
||||
## 4. Common Pitfalls & Gotchas
|
||||
|
||||
* **Code Injection:** Prevent code injection by validating all input data.
|
||||
* **Denial of Service (DoS):** Protect against DoS attacks by limiting resource usage.
|
||||
* **Man-in-the-Middle (MitM):** Use encryption to protect data in transit.
|
||||
* **Data Tampering:** Prevent data tampering by using checksums and digital signatures.
|
||||
* **Save Game Manipulation:** Protect save game data from modification to prevent cheating.
|
||||
### 4.1 Blueprint Overuse for Performance
|
||||
|
||||
### 4.2 Input Validation
|
||||
Avoid implementing complex, frequently-called, or performance-critical logic exclusively in Blueprints. Profile your game to identify bottlenecks.
|
||||
|
||||
* **Validate All Input Data:** Validate all input data from players and external sources.
|
||||
* **Sanitize Input Data:** Sanitize input data to remove potentially malicious characters or code.
|
||||
* **Limit Input Length:** Limit the length of input strings to prevent buffer overflows.
|
||||
* **Use Regular Expressions:** Use regular expressions to validate input patterns.
|
||||
* **Implement Whitelists:** Use whitelists to define allowed characters and patterns.
|
||||
❌ **BAD**
|
||||
```blueprint
|
||||
// In a Tick event or a loop that runs many times
|
||||
// -> Complex mathematical calculations or array operations
|
||||
// -> Heavy string manipulations
|
||||
```
|
||||
|
||||
### 4.3 Authentication and Authorization
|
||||
✅ **GOOD**
|
||||
```cpp
|
||||
// C++: Implement the core complex logic
|
||||
UFUNCTION(BlueprintCallable, Category = "Calculations")
|
||||
float CalculateComplexValue(float Input);
|
||||
```
|
||||
```blueprint
|
||||
// Blueprint: Call the optimized C++ function
|
||||
// -> Call CalculateComplexValue (C++ function)
|
||||
```
|
||||
|
||||
* **Use Secure Authentication Methods:** Use secure authentication methods such as OAuth 2.0 or JWT.
|
||||
* **Implement Role-Based Access Control (RBAC):** Use RBAC to control access to different features and resources.
|
||||
* **Use Strong Passwords:** Enforce the use of strong passwords.
|
||||
* **Implement Multi-Factor Authentication (MFA):** Use MFA for added security.
|
||||
* **Store Credentials Securely:** Store user credentials securely using encryption and salting.
|
||||
* **Avoid Storing Secrets in Code:** Use configuration files or environment variables to store sensitive information.
|
||||
### 4.2 Unnecessary `UObject` Inheritance
|
||||
|
||||
### 4.4 Data Protection
|
||||
Only inherit from `UObject` (or its derivatives like `AActor`, `UDataAsset`, `UWidget`) when you need Unreal's reflection system, garbage collection, editor integration, or Blueprint exposure. For simple helper classes or data structures, use plain C++ classes or structs.
|
||||
|
||||
* **Encrypt Sensitive Data:** Encrypt sensitive data at rest and in transit.
|
||||
* **Use Secure Communication Protocols:** Use HTTPS for secure communication over the network.
|
||||
* **Protect Save Game Data:** Encrypt save game data to prevent cheating.
|
||||
* **Implement Data Backups:** Regularly back up data to prevent data loss.
|
||||
* **Comply with Data Privacy Regulations:** Comply with data privacy regulations such as GDPR and CCPA.
|
||||
* **Avoid Exposing Debug Information in Release Builds:** Disable or remove debug information in release builds.
|
||||
❌ **BAD**
|
||||
```cpp
|
||||
// UCLASS for a simple utility that doesn't need reflection or GC
|
||||
UCLASS()
|
||||
class UMySimpleHelper
|
||||
{
|
||||
GENERATED_BODY()
|
||||
public:
|
||||
void DoSomething();
|
||||
};
|
||||
```
|
||||
|
||||
### 4.5 Secure API Communication
|
||||
|
||||
* **Use API Keys:** Use API keys to authenticate API requests.
|
||||
* **Implement Rate Limiting:** Implement rate limiting to prevent abuse of API endpoints.
|
||||
* **Use Input Validation:** Utilize robust input validation on APIs
|
||||
* **Use Secure Communication Protocols:** Use HTTPS for secure communication over the network.
|
||||
* **Validate API Responses:** Validate API responses to ensure data integrity.
|
||||
* **Log API Requests and Responses:** Log API requests and responses for auditing and monitoring.
|
||||
✅ **GOOD**
|
||||
```cpp
|
||||
// Plain C++ class for a simple utility
|
||||
class FMySimpleHelper
|
||||
{
|
||||
public:
|
||||
void DoSomething();
|
||||
};
|
||||
```
|
||||
|
||||
## 5. Testing Approaches
|
||||
|
||||
### 5.1 Unit Testing
|
||||
### 5.1 Automated Tests
|
||||
|
||||
* **Test Individual Components:** Write unit tests for individual components and classes.
|
||||
* **Use a Testing Framework:** Use a testing framework such as Unreal Engine's built-in Automation System or third-party frameworks.
|
||||
* **Write Clear and Concise Tests:** Write tests that are easy to understand and maintain.
|
||||
* **Test Edge Cases:** Test edge cases and boundary conditions.
|
||||
* **Use Mock Objects:** Use mock objects to isolate components during testing.
|
||||
* **Test Driven Development:** Consider using Test Driven Development (TDD) principles.
|
||||
* **Focus on Core Logic:** Prioritize testing core logic and critical functionalities.
|
||||
Implement automated tests for all critical C++ logic using Unreal's Automation Test Framework. This ensures code correctness and prevents regressions.
|
||||
|
||||
### 5.2 Integration Testing
|
||||
* **Unit Tests:** Verify individual functions and classes.
|
||||
* **Functional Tests:** Validate gameplay systems and interactions.
|
||||
|
||||
* **Test Interactions Between Components:** Write integration tests to test the interactions between different components and classes.
|
||||
* **Test Game Logic:** Test the overall game logic and flow.
|
||||
* **Test Data Flow:** Test the flow of data between different systems.
|
||||
* **Simulate Realistic Scenarios:** Simulate realistic game scenarios during integration testing.
|
||||
❌ **BAD**
|
||||
```cpp
|
||||
// No automated tests, relying solely on manual playtesting
|
||||
```
|
||||
|
||||
### 5.3 End-to-End Testing
|
||||
✅ **GOOD**
|
||||
```cpp
|
||||
// MyGame.Build.cs (add modules for testing)
|
||||
PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore" });
|
||||
PrivateDependencyModuleNames.AddRange(new string[] { "UnrealEd", "FunctionalTesting", "AutomationController" });
|
||||
|
||||
* **Test the Entire Game:** Test the entire game from start to finish.
|
||||
* **Use Automated Testing Tools:** Use automated testing tools to simulate player interactions.
|
||||
* **Test on Different Platforms:** Test on different platforms to ensure compatibility.
|
||||
* **Test with Real Players:** Test with real players to get feedback on gameplay and usability.
|
||||
// MyGameTest.cpp (example unit test)
|
||||
#include "CoreMinimal.h"
|
||||
#include "Misc/AutomationTest.h"
|
||||
#include "MyGame/Public/MyMathLibrary.h" // Assuming this is your class
|
||||
|
||||
### 5.4 Test Organization
|
||||
IMPLEMENT_SIMPLE_AUTOMATION_TEST(FMyMathLibraryAddTest, "MyGame.Math.Add", EAutomationTestFlags::ApplicationContextMask | EAutomationTestFlags::ProductFilter)
|
||||
|
||||
* **Organize Tests by Feature:** Organize tests by game features or modules.
|
||||
* **Create a Test Suite:** Create a test suite that can be run automatically.
|
||||
* **Use a Consistent Naming Convention:** Use a consistent naming convention for tests.
|
||||
* **Document Tests:** Document tests to explain their purpose and functionality.
|
||||
* **Keep Tests Up-to-Date:** Keep tests up-to-date with code changes.
|
||||
bool FMyMathLibraryAddTest::RunTest(const FString& Parameters)
|
||||
{
|
||||
// Arrange
|
||||
int A = 5;
|
||||
int B = 10;
|
||||
|
||||
### 5.5 Mocking and Stubbing
|
||||
// Act
|
||||
int Result = UMyMathLibrary::Add(A, B);
|
||||
|
||||
* **Use Mock Objects:** Use mock objects to simulate dependencies during testing.
|
||||
* **Use Stub Functions:** Use stub functions to replace complex or external functions.
|
||||
* **Isolate Components:** Isolate components during testing to avoid unintended interactions.
|
||||
* **Use a Mocking Framework:** Use a mocking framework such as Google Mock or EasyMock.
|
||||
// Assert
|
||||
TestEqual(TEXT("5 + 10 should be 15"), Result, 15);
|
||||
return true;
|
||||
}
|
||||
```
|
||||
|
||||
## 6. Common Pitfalls and Gotchas
|
||||
### 5.2 Blueprint Validation
|
||||
|
||||
### 6.1 Frequent Mistakes
|
||||
Add robust validation within Blueprints, especially for data assets, critical paths, and user inputs. Use `IsValid` checks and `ensure`/`check` in C++ code exposed to Blueprint.
|
||||
|
||||
* **Incorrect Asset Management:** Failing to properly manage and reference assets.
|
||||
* **Over-Reliance on Blueprints:** Overusing Blueprints for complex logic, leading to performance issues.
|
||||
* **Ignoring Performance Considerations:** Neglecting to optimize code and assets for performance.
|
||||
* **Poor Memory Management:** Creating memory leaks and excessive garbage collection.
|
||||
* **Inadequate Error Handling:** Failing to handle errors and exceptions gracefully.
|
||||
* **Lack of Testing:** Not writing adequate unit and integration tests.
|
||||
* **Incorrect use of transform:** Using world transform directly, instead of relative transform for attached components.
|
||||
* **Not using the Garbage Collector Properly:** Not understanding when and how the Unreal Engine garbage collector reclaims memory.
|
||||
❌ **BAD**
|
||||
```blueprint
|
||||
// Assuming 'MyActorReference' is always valid
|
||||
// -> MyActorReference.DoSomething()
|
||||
```
|
||||
|
||||
### 6.2 Edge Cases
|
||||
|
||||
* **Platform-Specific Issues:** Encountering platform-specific bugs or limitations.
|
||||
* **Device-Specific Issues:** Encountering device-specific performance issues.
|
||||
* **Localization Issues:** Encountering issues with text localization and internationalization.
|
||||
* **Save Game Corruption:** Dealing with corrupted save game data.
|
||||
* **Network Latency:** Handling network latency and packet loss in multiplayer games.
|
||||
|
||||
### 6.3 Version-Specific Issues
|
||||
|
||||
* **API Changes:** Dealing with API changes between Unreal Engine versions.
|
||||
* **Deprecated Features:** Using deprecated features that may be removed in future versions.
|
||||
* **Compatibility Issues:** Encountering compatibility issues between different Unreal Engine versions.
|
||||
* **Shader Model Differences:** Accounting for differences in shader models across different UE versions.
|
||||
|
||||
### 6.4 Compatibility Concerns
|
||||
|
||||
* **Plugin Compatibility:** Ensuring compatibility between different plugins.
|
||||
* **Hardware Compatibility:** Ensuring compatibility with different hardware configurations.
|
||||
* **Operating System Compatibility:** Ensuring compatibility with different operating systems.
|
||||
* **Third-Party Library Compatibility:** Ensuring compatibility with third-party libraries and SDKs.
|
||||
|
||||
### 6.5 Debugging Strategies
|
||||
|
||||
* **Use the Unreal Engine Debugger:** Use the Unreal Engine debugger to step through code and inspect variables.
|
||||
* **Use Logging Statements:** Use logging statements to track the flow of execution and identify errors.
|
||||
* **Use Breakpoints:** Set breakpoints in the code to pause execution at specific points.
|
||||
* **Use the Visual Logger:** Use the Visual Logger to visualize game data and events.
|
||||
* **Use Unreal Insights:** Use Unreal Insights to profile performance and identify bottlenecks.
|
||||
* **Crash Reporting:** Implement crash reporting to collect crash logs and diagnose issues.
|
||||
|
||||
## 7. Tooling and Environment
|
||||
|
||||
### 7.1 Recommended Development Tools
|
||||
|
||||
* **Visual Studio:** For C++ development on Windows.
|
||||
* **XCode:** For C++ development on macOS.
|
||||
* **Rider for Unreal Engine:** Cross-platform IDE for Unreal Engine development with C++ and Blueprints.
|
||||
* **Substance Painter:** For creating and texturing materials.
|
||||
* **Blender/Maya/3ds Max:** For creating 3D models and animations.
|
||||
* **Perforce/Git:** For version control.
|
||||
* **RenderDoc/PIX:** For GPU debugging and profiling.
|
||||
|
||||
### 7.2 Build Configuration
|
||||
|
||||
* **Use Development Builds:** Use development builds for debugging and testing.
|
||||
* **Use Shipping Builds:** Use shipping builds for release.
|
||||
* **Configure Build Settings:** Configure build settings such as optimization level and debug information.
|
||||
* **Use Build Automation:** Use build automation tools to automate the build process.
|
||||
* **Set up Build Targets:** Properly configure build targets based on desired device platform (desktop, mobile, console, etc.)
|
||||
|
||||
### 7.3 Linting and Formatting
|
||||
|
||||
* **Use a Code Linter:** Use a code linter to enforce code style and identify potential errors.
|
||||
* **Use a Code Formatter:** Use a code formatter to automatically format code.
|
||||
* **Follow the Unreal Engine Coding Standard:** Follow the Unreal Engine coding standard for consistency.
|
||||
* **Configure Editor Settings:** Configure editor settings to automatically format code on save.
|
||||
|
||||
### 7.4 Deployment
|
||||
|
||||
* **Package the Game:** Package the game for the target platform.
|
||||
* **Test the Packaged Game:** Test the packaged game thoroughly before release.
|
||||
* **Use a Deployment Platform:** Use a deployment platform such as Steam or the Epic Games Store.
|
||||
* **Follow Platform-Specific Requirements:** Follow platform-specific requirements for deployment.
|
||||
|
||||
### 7.5 CI/CD Integration
|
||||
|
||||
* **Use a CI/CD System:** Use a CI/CD system such as Jenkins, Travis CI, or GitLab CI.
|
||||
* **Automate Builds and Tests:** Automate builds and tests as part of the CI/CD pipeline.
|
||||
* **Integrate with Version Control:** Integrate the CI/CD system with the version control system.
|
||||
* **Automate Deployment:** Automate deployment to the target platform as part of the CI/CD pipeline.
|
||||
* **Trigger Builds on Code Changes:** Configure the CI/CD system to trigger builds automatically on code changes.
|
||||
✅ **GOOD**
|
||||
```blueprint
|
||||
// Always check validity before dereferencing
|
||||
// Input: MyActorReference (Actor Object Reference)
|
||||
// -> IsValid (MyActorReference)
|
||||
// --- IF TRUE ---
|
||||
// -> MyActorReference.DoSomething()
|
||||
// --- IF FALSE ---
|
||||
// -> Print String "Error: MyActorReference is null!"
|
||||
```
|
||||
Reference in New Issue
Block a user