### Unreal Engine C++ Gameplay Timers Source: https://context7.com/mrrobinofficial/guide-unrealengine/llms.txt Demonstrates setting up one-shot and repeating timers using the TimerManager. Includes examples for starting timers with specific delays and rates, clearing individual timers, and checking timer status. Timers are crucial for gameplay mechanics like cooldowns and periodic effects. ```cpp // MyActor.h class AMyActor : public AActor { GENERATED_BODY() protected: FTimerHandle ExplosionTimerHandle; FTimerHandle DamageTimerHandle; UFUNCTION() void OnExplode(); UFUNCTION() void ApplyDamage(int32 DamageAmount); public: void ActivateBomb(); void StartToxicGas(); void StopToxicGas(); }; // MyActor.cpp void AMyActor::ActivateBomb() { // One-shot timer: explode after 3 seconds float Delay = 3.0f; bool bLooping = false; GetWorld()->GetTimerManager().SetTimer( ExplosionTimerHandle, this, &AMyActor::OnExplode, Delay, bLooping ); } void AMyActor::StartToxicGas() { // Repeating timer: apply damage every 1 second FTimerDelegate DamageDelegate; DamageDelegate.BindUFunction(this, &AMyActor::ApplyDamage, 10); float Rate = 1.0f; bool bLoop = true; GetWorld()->GetTimerManager().SetTimer( DamageTimerHandle, DamageDelegate, Rate, bLoop ); // Check timer status bool bIsActive = GetWorld()->GetTimerManager().IsTimerActive(DamageTimerHandle); float TimeRemaining = GetWorld()->GetTimerManager().GetTimerRemaining(DamageTimerHandle); } void AMyActor::StopToxicGas() { // Clear specific timer GetWorld()->GetTimerManager().ClearTimer(DamageTimerHandle); // Or clear all timers for this object // GetWorld()->GetTimerManager().ClearAllTimersForObject(this); } void AMyActor::OnExplode() { UE_LOG(LogTemp, Warning, TEXT("Bomb exploded!")); } void AMyActor::ApplyDamage(int32 DamageAmount) { UE_LOG(LogTemp, Log, TEXT("Applied %d damage"), DamageAmount); } ``` -------------------------------- ### UPROPERTY Config and GlobalConfig Example Source: https://github.com/mrrobinofficial/guide-unrealengine/blob/main/sections/unreal_header_tool.md Demonstrates the Config and GlobalConfig specifiers for serializing properties to project and global configuration files, respectively. ```cpp // Must mark UCLASS with Config specifier // Config can be overriden from the base class. UPROPERTY(Config, BlueprintReadOnly) bool bRegenerateHealth; // GlobalConfig CANNOT be overridden from the base class. UPROPERTY(GlobalConfig, BlueprintReadOnly) bool bEnableHealthSimulation; ``` -------------------------------- ### UPROPERTY Meta Units Example Source: https://github.com/mrrobinofficial/guide-unrealengine/blob/main/sections/unreal_header_tool.md Demonstrates using the meta specifier with Units to define human-readable units for properties in the editor. ```cpp UPROPERTY(EditAnywhere, meta=(Units="Celsius")) float CookingTemperature; UPROPERTY(EditAnywhere, meta=(Units="Kilograms")) float TigerWeight; UPROPERTY(EditAnywhere, meta=(Units="GB")) float DiskSpace; UPROPERTY(EditAnywhere, meta=(Units="Percent")) float Happiness; UPROPERTY(EditAnywhere, meta=(Units="times")) float Deliciousness; ``` -------------------------------- ### UPROPERTY EditAnywhere Example Source: https://github.com/mrrobinofficial/guide-unrealengine/blob/main/sections/unreal_header_tool.md Demonstrates using EditAnywhere to allow editing of a property in the editor and at runtime. It also includes an example of categorizing the property. ```cpp UPROPERTY(EditAnywhere, Category="Hello|Cruel|World") int32 EditAnywhereNumber; ``` -------------------------------- ### UFUNCTION BlueprintPure Example Source: https://github.com/mrrobinofficial/guide-unrealengine/blob/main/sections/unreal_header_tool.md Demonstrates using BlueprintPure to expose a pure function (no side effects) to Blueprint scripting. ```cpp UFUNCTION(BlueprintPure) int32 AddNumbers(int32 a, int32 b); ``` -------------------------------- ### UFUNCTION BlueprintCallable Example Source: https://github.com/mrrobinofficial/guide-unrealengine/blob/main/sections/unreal_header_tool.md Illustrates how to use BlueprintCallable to expose a function to Blueprint scripting. ```cpp UFUNCTION(BlueprintCallable) void MyBlueprintFunction(); ``` -------------------------------- ### String Builder with Type Formatting Example Source: https://github.com/mrrobinofficial/guide-unrealengine/blob/main/sections/data_types.md Practical example of using string builder for formatted output with multiple data types. Shows how to combine text literals with formatted numeric values using Unreal Engine's stream-style operators and return the constructed string for use in calling code. ```cpp TStringBuilder<256> MessageBuilder; float PlayerHealth = 110.5285f; MessageBuilder << TEXTVIEW("Player's health: ") << FString::SanitizeFloat(PlayerHealth); return FString { MessageBuilder }; ``` -------------------------------- ### UFUNCTION BlueprintImplementableEvent Example Source: https://github.com/mrrobinofficial/guide-unrealengine/blob/main/sections/unreal_header_tool.md Shows how to use BlueprintImplementableEvent to create a placeholder function that can be overridden in Blueprint. ```cpp UFUNCTION(BlueprintImplementableEvent) void MyBlueprintEvent(); ``` -------------------------------- ### UE_LOGFMT with Named Arguments Source: https://github.com/mrrobinofficial/guide-unrealengine/blob/main/sections/logging.md Demonstrates logging using UE_LOGFMT with named arguments, allowing for more readable log messages by explicitly naming each variable. This example shows logging a package name, error code, and flags. ```cpp UE_LOGFMT(LogCore, Warning, "Loading '{Name}' failed with error {Error}", ("Error", ErrorCode), ("Name", Package->GetName()), ("Flags", LoadFlags)); ``` -------------------------------- ### UPROPERTY Transient and Replicated Example Source: https://github.com/mrrobinofficial/guide-unrealengine/blob/main/sections/unreal_header_tool.md Shows how to use Transient and Replicated specifiers for properties that should not persist and should be replicated in a multiplayer environment. Includes a custom replication function. ```cpp UPROPERTY(Transient, Replicated) int32 CurrentHealth; UPROPERTY(Transient, ReplicatedUsing=OnArmorChanged) int32 CurrentArmor; UFUNCTION() void OnArmorChanged(); ``` -------------------------------- ### C++ Unreal Engine HTTP Request Example Usage Source: https://github.com/mrrobinofficial/guide-unrealengine/blob/main/sections/deep_dive.md This C++ code demonstrates how to initiate an HTTP GET request in Unreal Engine and handle the response. It shows how to define URLs, set up a delegate for the callback, and call the SendRequest function. The response is processed in the OnRequestCompleted function. ```cpp // Final URL: BASE_URL + ENDPOINT_URL = "https://swapi.dev/api/planets/3/" // Helpful to split the endpoint, as you can switch to another endpoint. const FString BASE_URL = "https://swapi.dev/api/"; const FString ENDPOINT_URL = "planets/3/"; // "starships/9/", "people/1/" FString JSON; FHTTPRequest Delegate; Delegate.BindDynamic(this, &YourClass::OnRequestCompleted); // Send the request with delegate passed into the parameters SendRequest(BASE_URL, ENDPOINT_URL, EHTTPRequestType::GET, "", Delegate); void YourClass::OnRequestCompleted(const FString& Result, bool bWasSuccessful) { if (!bWasSuccessful) { UE_LOGFMT(LogTemp, Log, "The Request was not successful!"); return; } UE_LOGFMT(LogTemp, Log, "Request Output: {0}", Result); } ``` -------------------------------- ### Unreal Engine PI and Macro Examples Source: https://github.com/mrrobinofficial/guide-unrealengine/blob/main/sections/macros.md Provides examples of defining the PI constant and a macro for multiplying a value by PI in C++. These are common preprocessor directives for mathematical constants and operations. ```cpp #define PI 3.14 #define PI_MULTIPLY(x) 3.14 * x ``` -------------------------------- ### Log Messages Using UE_LOG Macro Source: https://github.com/mrrobinofficial/guide-unrealengine/blob/main/sections/logging.md Provides practical UE_LOG macro examples for logging different data types. Includes simple string messages, FString formatting with %s specifier, and boolean variable declaration pattern for logging. Each example shows proper TEXT() macro usage and verbosity level specification. ```cpp UE_LOG(LogTemp, Warning, TEXT("Hello")); ``` ```cpp UE_LOG(LogTemp, Warning, TEXT("The Actor's name is: %s"), *YourActor->GetName()); ``` ```cpp bool bMyBoolean = true; ``` -------------------------------- ### Basic C++ constructor example Source: https://github.com/mrrobinofficial/guide-unrealengine/blob/main/backups/README_2023_12_10.md Simple C++ constructor syntax showing initialization of a class instance. No parameters in this example. ```cpp class RegularClass { RegularClass() { // Constructor called } }; ``` -------------------------------- ### UPROPERTY SimpleDisplay and AdvancedDisplay Example Source: https://github.com/mrrobinofficial/guide-unrealengine/blob/main/sections/unreal_header_tool.md Illustrates how to use SimpleDisplay and AdvancedDisplay specifiers to control the appearance of a property in the editor's Details panel. ```cpp UPROPERTY(EditAnywhere, SimpleDisplay) int32 MaxHealth = 100; UPROPERTY(EditAnywhere, AdvancedDisplay) float HealthRegenerationTime = 5.0f; ``` -------------------------------- ### Unreal Engine String Types (C++) Source: https://context7.com/mrrobinofficial/guide-unrealengine/llms.txt Shows Unreal's string types (FString, FName, FText) with initialization examples for dynamic strings, immutable names, and localized text. ```cpp FString DynamicString = TEXT("Hello World"); FName FastName = FName(TEXT("UniqueIdentifier")); FText LocalizedText = NSLOCTEXT("Game", "Welcome", "Welcome Player!"); ``` -------------------------------- ### UFUNCTION BlueprintNativeEvent Example Source: https://github.com/mrrobinofficial/guide-unrealengine/blob/main/sections/unreal_header_tool.md Demonstrates using BlueprintNativeEvent to expose a function with a default C++ implementation to Blueprint for optional overriding. ```cpp UFUNCTION(BlueprintNativeEvent) void MyBlueprintEvent(); ``` -------------------------------- ### UPROPERTY Macro Example Source: https://github.com/mrrobinofficial/guide-unrealengine/blob/main/README.md Shows an example of the UPROPERTY macro, used to declare properties for Unreal Engine's reflection system. ```cpp UPROPERTY([specifier1=setting1, specifier2, ...], [meta=(key1=\"value1\", key2=\"value2\", ...)]) ``` -------------------------------- ### Basic UE_LOGFMT Usage Source: https://github.com/mrrobinofficial/guide-unrealengine/blob/main/sections/logging.md Includes the necessary header file and demonstrates the basic usage of the UE_LOGFMT macro for logging simple messages to the console. ```cpp #include "Logging/StructuredLog.h" UE_LOGFMT(LogTemp, Log, "This message will print to my log"); ``` -------------------------------- ### Inline function example (C++) Source: https://github.com/mrrobinofficial/guide-unrealengine/blob/main/sections/keywords.md Shows basic inline function usage where the compiler may replace calls with direct code insertion. Compiler decides whether to honor inline requests. ```cpp inline int CalcNewHealth(int Health) { return Health - 10; } const int Health = 10; Health = CalcNewHealth(Health); // Potential inline: Health = 10 - 10; ``` -------------------------------- ### Unreal Engine Logging System (UE_LOG) Examples Source: https://context7.com/mrrobinofficial/guide-unrealengine/llms.txt Illustrates how to use Unreal Engine's logging system (UE_LOG) for debugging and monitoring. It covers defining custom log categories, basic logging with different verbosity levels, logging variables with formatting, logging complex types, displaying on-screen debug messages, and using the modern UE_LOGFMT macro available in UE 5.2+. ```cpp // Define custom log category in header // MyClass.h DECLARE_LOG_CATEGORY_EXTERN(MyLogCategory, Log, All); // MyClass.cpp DEFINE_LOG_CATEGORY(MyLogCategory); // Basic logging examples UE_LOG(LogTemp, Warning, TEXT("Hello")); UE_LOG(MyLogCategory, Error, TEXT("Critical error occurred")); // Logging with variable formatting FString ActorName = TEXT("PlayerCharacter"); int32 Health = 100; float Speed = 5.5f; bool bIsAlive = true; UE_LOG(LogTemp, Warning, TEXT("Actor: %s, Health: %d"), *ActorName, Health); UE_LOG(LogTemp, Log, TEXT("Speed: %.2f m/s"), Speed); UE_LOG(LogTemp, Log, TEXT("Is Alive: %s"), (bIsAlive ? TEXT("true") : TEXT("false"))); // Logging complex types FVector Location = FVector(100.0f, 200.0f, 300.0f); UE_LOG(LogTemp, Display, TEXT("Location: %s"), *Location.ToString()); // On-screen debug messages if (GEngine) { GEngine->AddOnScreenDebugMessage(-1, 5.0f, FColor::Red, FString::Printf(TEXT("Health: %d, Speed: %.2f"), Health, Speed)); } // Modern UE_LOGFMT (UE 5.2+) #include "Logging/StructuredLog.h" UE_LOGFMT(LogTemp, Log, "Loading '{0}' with value {1}", ActorName, Health); UE_LOGFMT(LogCore, Warning, "Error {Error} loading {Name}", ("Error", ErrorCode), ("Name", PackageName)); ``` -------------------------------- ### Initialize FIntPoint and FUIntPoint in C++ Source: https://github.com/mrrobinofficial/guide-unrealengine/blob/main/sections/data_types.md Shows how to declare and initialize 2D integer points using FIntPoint for signed integers and FUIntPoint for unsigned integers. Examples include initializing with specific values and demonstrating the typical range for signed and unsigned 8-bit integers. ```cpp FIntPoint MinPoint = FIntPoint(-127, -127); FIntPoint MaxPoint = FIntPoint(128, 128); FUIntPoint UnsignedMinPoint = FUIntPoint(0, 0); FUintPoint UnsignedMaxPoint = FUIntPoint(255, 255); ``` -------------------------------- ### Instantiate and Start FRunnable Thread (C++) Source: https://github.com/mrrobinofficial/guide-unrealengine/blob/main/backups/README_2023_12_10.md Demonstrates how to create and start an instance of a custom FRunnable thread. This involves dynamically allocating a new FMyThread object. The pointer to the thread object should be managed carefully. Dependencies: The FMyThread class definition. ```cpp auto* Thread = new FMyThread( /*Parameters*/ ); ``` -------------------------------- ### Unreal Engine TMap: Iterating Through Key-Value Pairs Source: https://github.com/mrrobinofficial/guide-unrealengine/blob/main/sections/data_types.md Provides an example of how to iterate over all key-value pairs in a TMap using a range-based for loop and log each pair's key and value. ```cpp for (const TPair& KeyValuePair : MyMap) { UE_LOG(LogTemp, Log, TEXT("Key: %s, Value: %i"), *KeyValuePair.Key.ToString(), KeyValuePair.Value); } ``` -------------------------------- ### Unreal Engine Macros Example Source: https://github.com/mrrobinofficial/guide-unrealengine/blob/main/README.md Shows examples of common Unreal Engine macros: UPROPERTY, UFUNCTION, UCLASS, USTRUCT, UENUM, UPARAM, and UMETA. ```cpp UPROPERTY([specifier1=setting1, specifier2, ...], [meta=(key1=\"value1\", key2=\"value2\", ...)])) UFUNCTION([specifier1=setting1, specifier2, ...], [meta=(key1=\"value1\", key2=\"value2\", ...)])) UCLASS([specifier1=setting1, specifier2, ...], [meta=(key1=\"value1\", key2=\"value2\", ...)])) USTRUCT([specifier1=setting1, specifier2, ...], [meta=(key1=\"value1\", key2=\"value2\", ...)])) UENUM([specifier1=setting1, specifier2, ...]) UPARAM([specifier1=setting1, specifier2, ...]) UMETA([specifier1=setting1, specifier2, ...]) ``` -------------------------------- ### C++ Unreal Engine Example HTTP Request Call Source: https://github.com/mrrobinofficial/guide-unrealengine/blob/main/README.md Demonstrates how to call the SendRequest function in Unreal Engine to perform an HTTP GET request to the Star Wars API. It includes setting up the base and endpoint URLs, defining a delegate for the callback, and handling the response. ```cpp void YourClass::SendTestRequest() { // Final URL: BASE_URL + ENDPOINT_URL = "https://swapi.dev/api/planets/3/" // Helpful to split the endpoint, as you can switch to another endpoint. const FString BASE_URL = "https://swapi.dev/api/"; const FString ENDPOINT_URL = "planets/3/"; // "starships/9/", "people/1/" FString JSON; FHTTPRequest Delegate; Delegate.BindDynamic(this, &YourClass::OnRequestCompleted); // Send the request with delegate passed into the parameters SendRequest(BASE_URL, ENDPOINT_URL, EHTTPRequestType::GET, "", Delegate); } void YourClass::OnRequestCompleted(const FString& Result, bool bWasSuccessful) { if (!bWasSuccessful) { UE_LOGFMT(LogTemp, Log, "The Request was not successful!"); return; } UE_LOGFMT(LogTemp, Log, "Request Output: {0}", Result); } ``` -------------------------------- ### Start Analytics Session in C++ Source: https://github.com/mrrobinofficial/guide-unrealengine/blob/main/sections/libraries.md Demonstrates the `StartSession()` function within a Blueprint Function Library. This function starts an analytics session using the default configured provider. It handles cases where the provider is invalid and logs a warning. ```cpp UCLASS() class UAnalyticsBlueprintLibrary : public UBlueprintFunctionLibrary { GENERATED_UCLASS_BODY() public: /** Starts an analytics session without any custom attributes specified */ UFUNCTION(BlueprintCallable, Category = "Analytics") static bool StartSession(); } bool UAnalyticsBlueprintLibrary::StartSession() { TSharedPtr Provider = FAnalytics::Get().GetDefaultConfiguredProvider(); if (Provider.IsValid()) return Provider->StartSession(); else { UE_LOG( LogAnalyticsBPLib, Warning, TEXT("StartSession: Failed to get the default analytics provider. Double check your [Analytics] configuration in your INI") ); } return false; } ``` -------------------------------- ### Starting an FRunnable Thread in Unreal Engine Source: https://github.com/mrrobinofficial/guide-unrealengine/blob/main/README.md Demonstrates how to instantiate and start a custom `FRunnable` thread in Unreal Engine. It requires including the thread's header and creating a new instance of the thread class. ```cpp auto* Thread = new FMyThread( /*Parameters*/ ); ``` -------------------------------- ### C++ Struct, Reference, and Pointer Example Source: https://github.com/mrrobinofficial/guide-unrealengine/blob/main/sections/data_types.md This C++ code defines a `Coords` struct with a constructor and a `toString` method. The `main` function demonstrates the creation of structs, assignments to references and pointers, modification of members through references and pointers, dynamic allocation, and deallocation. ```cpp // Test struct and class struct Coords { // Constructor: Initialize X and Y with given values Coords(int x, int y) : X(x), Y(y) {} public: int X; // X coordinate int Y; // Y coordinate public: // Return a string representation of this Coords struct std::string toString() const { // Use stringstream to concatenate strings std::stringstream ss; ss << "(" << X << ", " << Y << ")"; return ss.str(); } }; int main() { Coords A(1, 2); // Create struct A Coords& B = A; // B is a reference to A Coords* C = &B; // C is a pointer to A Coords* D = new Coords(5, 10); // Create a new Coords struct with new Coords* E = &(*C); // E is a pointer to what C points to B.X = 69; // Modify X of A through B C->Y = 1337; // Modify Y of A through C D->Y = D->Y * 2; // Modify Y of dynamically allocated struct E = &*D; // Make E point to what D points to E->X = 10; // Modify X of dynamically allocated struct // Print statements std::cout << A.toString() << std::endl; std::cout << B.toString() << std::endl; std::cout << C->toString() << std::endl; std::cout << D->toString() << std::endl; std::cout << E->toString() << std::endl; delete D; // Deallocate memory of dynamically allocated struct return 0; } ``` -------------------------------- ### Unreal Engine UFUNCTION with Meta Tags Source: https://github.com/mrrobinofficial/guide-unrealengine/blob/main/sections/unreal_header_tool.md Shows how to use meta tags with UFUNCTION to customize its behavior and appearance in the Unreal Editor. This example sets a custom return display name for a BlueprintCallable function. ```cpp UFUNCTION(BlueprintCallable, Category = "Doggy Daycare", meta=(ReturnDisplayName = "Success")) bool TryPetDog(const FName Name); ``` -------------------------------- ### TList Initialization and Traversal Example in C++ Source: https://github.com/mrrobinofficial/guide-unrealengine/blob/main/README.md Demonstrates how to create and manipulate a TList in C++. It includes initializing the head node, adding new nodes, modifying elements, and traversing the list to print each element's value. This example illustrates the manual memory management required with TList. ```cpp // Create the head of the list with data value of 69 TList Head(69); // Create a new node with data 1337 and link it to the head Head.Next = new TList(1337); // Create another node with data 3 and link it to the previous node Head.Next->Next = new TList(3); // Re-assign the data value Head.Next->Next->Next.Element = 420; // Print the elements in the linked list TList* CurrentNode = &Head; while (CurrentNode != nullptr) { UE_LOG(LogTemp, Log, TEXT("Element: %i"), CurrentNode->Element); CurrentNode = CurrentNode->Next; } ``` -------------------------------- ### Unreal Engine Algo: IndexOf, Transform, Reverse, Sort, ForEach Examples (C++) Source: https://github.com/mrrobinofficial/guide-unrealengine/blob/main/sections/data_types.md Demonstrates common operations using the Unreal Engine's Algo namespace. Includes finding an element's index, transforming elements to uppercase, reversing an array, sorting numerically, sorting by absolute value, applying a function to each element, and custom sorting logic. Requires core headers for Algo functions and TArray. ```cpp #include "Algo/ForEach.h" #include "Algo/Accumulate.h" #include "Algo/IndexOf.h" TArray Array; Array.Add(TEXT("hello")); Array.Add(TEXT("cRuEL")); Array.Add(TEXT("WORLD")); const int32 FoundIndex = Algo::IndexOf(Array, FString(TEXT("cRuEL"))); if (FoundIndex != INDEX_NONE) { // Successfully found the index } const int32 FoundIndexPred = Algo::IndexOfByPredicate(Array, [&](const FString& Arg) { return TEXT("hello") == Arg.ToLower(); }); if (FoundIndexPred != INDEX_NONE) { // Successfully found the index with prediction } TArray TransformArray; Algo::Transform(Array, TransformArray, [](const FString& Item) { return Item.ToUpper(); }); // { "HELLO", "CRUEL", "WORLD" } Algo::Reverse(TransformArray); // { "WORLD", "CRUEL", "HELLO" } TArray SortArray { 1, 5, 3, -4, 2, -1 }; Algo::Sort(SortArray); // { -4, -1, 1, 2, 3, 5 } // Create a lambda function for this projection auto AbsProjection = [](int32 Value) { return FMath::Abs(Value); }; // Will sort based on this projection. But will still reserve the original values. Algo::SortBy(SortArray, AbsProjection); // { -1, 1, 2, 3, -4, 5 } Algo::ForEach(SortArray, [](int32& Value) { Value *= 2; }); // { -2, 2, 4, 6, -8, 10 } // Will sort based on descending order auto ReverseSortPredicate = [](int32 A, int32 B) { return A > B; }; Algo::SortBy(SortArray, AbsProjection, ReverseSortPredicate); // { 10, -8, 6, 4, 2, -2 } ``` -------------------------------- ### Character Data Type Declarations (C++ vs Unreal) Source: https://github.com/mrrobinofficial/guide-unrealengine/blob/main/sections/data_types.md Demonstrates character type declarations in native C++ using 'char' versus Unreal's 'TCHAR' type, which adapts to platform requirements. The examples show basic character initialization and the difference between standard C++ and Unreal's character handling. ```cpp char myChar = 'a'; ``` ```cpp TCHAR MyChar = 'A'; ``` -------------------------------- ### Unreal Engine TArray: Declaration and Basic Operations (C++) Source: https://github.com/mrrobinofficial/guide-unrealengine/blob/main/sections/data_types.md Demonstrates how to declare a TArray, add, append, and remove elements. Includes examples for getting the array size and iterating through its elements using a range-based for loop. Assumes the Unreal Engine environment and logging system (UE_LOG). ```cpp #include "Containers/Array.h" TArray MyArray { 1, 2, 3 }; MyArray.Add(4); MyArray.Append({10, 15, 20}); MyArray.RemoveAt(0); MyArray.RemoveAt(0); int32 NumOfElements = MyArray.Num(); // 5 for (const int32& Element : MyArray) { UE_LOG(LogTemp, Log, TEXT("Element: %i"), Element); } ``` -------------------------------- ### Unreal Engine TQueue: Thread-Safe Queue Example (C++) Source: https://github.com/mrrobinofficial/guide-unrealengine/blob/main/README.md Provides a C++ example for using TQueue, an unbounded, thread-safe queue implemented with a lock-free linked list. Demonstrates enqueuing and dequeuing elements of type FHitResult, checking if the queue is empty, and iterating through its contents. ```cpp #include "Containers/Queue.h" TQueue MyQueue; // Example FHitResult data AActor* TargetActor = this; UPrimitiveComponent* TargetComponent = this; FVector HitLocation = FVector(900.0f, 0.0f, 500.0f); FVector HitNormal = FVector(0.0f, 0.0f, 1.0f); MyQueue.Enqueue(FHitResult(TargetActor, TargetComponent, HitLocation, HitNormal)); MyQueue.Enqueue(FHitResult(nullptr, nullptr, FVector::ZeroVector, FVector::OneVector.GetSafeNormal())); FHitResult DequeuedElement = MyQueue.Dequeue(); bool IsEmpty = MyQueue.IsEmpty(); while (!MyQueue.IsEmpty()) { FHitResult HitResult = MyQueue.Dequeue(); UE_LOG(LogTemp, Log, TEXT("Hit Target: %s"), *HitResult.GetActor()->GetName()); } ``` -------------------------------- ### Build Unreal Engine Plugin via Registry Query Source: https://github.com/mrrobinofficial/guide-unrealengine/blob/main/README.md Bash script that queries Windows registry to locate Unreal Engine installation path and executes the Automation Tool to build a plugin. Takes EngineVersion, PluginPath, OutputPath, and TargetPlatforms as inputs. Outputs the built plugin package and waits for user confirmation before exiting. ```bash EngineDirectory=$(reg query "HKEY_LOCAL_MACHINE\SOFTWARE\EpicGames\Unreal Engine\$EngineVersion" -v "InstalledDirectory" | awk 'NR==3{print $NF}') AutomationToolPath="$EngineDirectory/Engine/Build/BatchFiles/RunUAT.bat" echo "Automation Tool Path: \"$AutomationToolPath\"" echo $AutomationToolPath BuildPlugin -Plugin="$PluginPath" -Package="$OutputPath" -Rocket -TargetPlatforms="$TargetPlatforms" echo read -p "Press Enter to continue..." exit 0 ``` -------------------------------- ### Actor Initialization on Spawn Source: https://github.com/mrrobinofficial/guide-unrealengine/blob/main/README.md BeginPlay is called when an actor is spawned or respawned, similar to 'Start' or 'Awake' in other engines. It is ideal for setting default values, initializing components, and starting asynchronous tasks. This function takes no parameters and returns nothing. ```cpp void BeginPlay(); ``` -------------------------------- ### String Builder Initialization in C++ Source: https://github.com/mrrobinofficial/guide-unrealengine/blob/main/README.md Demonstrates how to include the necessary header for string builders and initialize them with either an unknown or a specified buffer size. The unknown size uses dynamic allocation, while the specified size attempts to allocate on the stack. ```cpp #include "Containers/StringFwd.h" // With unknown buffer size (uses dynamic memory allocation) FStringBuilderBase StringBuilder; // With initialized buffer size int32 BufferSize = 12; // 12 characters of TCHAR TStringBuilder StringBuilder; ``` -------------------------------- ### Implement Analytics Blueprint Function Library StartSession (C++) Source: https://github.com/mrrobinofficial/guide-unrealengine/blob/main/backups/README_2023_12_10.md Implements the `StartSession` function for the Analytics Blueprint Function Library. It attempts to get the default analytics provider and calls its `StartSession` method. Includes error logging if the provider is invalid. This function relies on the `FAnalytics` module and `IAnalyticsProvider` interface. ```cpp bool UAnalyticsBlueprintLibrary::StartSession() { TSharedPtr Provider = FAnalytics::Get().GetDefaultConfiguredProvider(); if (Provider.IsValid()) return Provider->StartSession(); else { UE_LOG( LogAnalyticsBPLib, Warning, TEXT("StartSession: Failed to get the default analytics provider. Double check your [Analytics] configuration in your INI") ); } return false; } ``` -------------------------------- ### Defining UPROPERTY Specifiers in C++ Source: https://context7.com/mrrobinofficial/guide-unrealengine/llms.txt This C++ code example illustrates various UPROPERTY specifiers used in an Unreal Engine actor class to manage property visibility in the editor, Blueprint accessibility, network replication, and metadata constraints. It requires inclusion of Unreal Engine headers like UObject, UClass, and replication setup. The class defines properties with different access levels and includes replication functions, but note that specifiers may have performance implications in large projects. ```cpp UCLASS() class AExampleActor : public AActor { GENERATED_BODY() public: // Visible and editable in editor and Blueprint UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Stats") int32 Health = 100; // Only visible in editor, not Blueprint accessible UPROPERTY(EditAnywhere, Category = "Config") float MovementSpeed = 600.0f; // Only editable on class defaults, not instances UPROPERTY(EditDefaultsOnly, Category = "Setup") TSubclassOf ProjectileClass; // Only editable on instances, not defaults UPROPERTY(EditInstanceOnly, Category = "Level Design") AActor* TargetActor; // Read-only in Blueprint UPROPERTY(BlueprintReadOnly, Category = "Runtime") bool bIsAlive = true; // Visible anywhere, read-only UPROPERTY(VisibleAnywhere, Category = "Debug") FString CurrentState; // Replicated over network UPROPERTY(Replicated) float ServerAuthorityValue; // Replicated with notification callback UPROPERTY(ReplicatedUsing = OnRep_Score) int32 Score; UFUNCTION() void OnRep_Score(); // Transient (not saved/loaded) UPROPERTY(Transient) float TemporaryValue; // Metadata for UI constraints UPROPERTY(EditAnywhere, Category = "Advanced", meta = (ClampMin = "0.0", ClampMax = "100.0", UIMin = "0.0", UIMax = "100.0")) float Percentage = 50.0f; UPROPERTY(EditAnywhere, Category = "Advanced", meta = (MakeEditWidget = true)) FVector TargetLocation; // Asset references UPROPERTY(EditAnywhere, Category = "Assets") TObjectPtr IconTexture; UPROPERTY(EditAnywhere, Category = "Assets") TSoftObjectPtr MeshAsset; // Container types UPROPERTY(EditAnywhere, Category = "Collections") TArray Numbers; UPROPERTY(EditAnywhere, Category = "Collections") TMap NamedValues; UPROPERTY(EditAnywhere, Category = "Collections") TSet TrackedActors; }; void AExampleActor::GetLifetimeReplicatedProps(TArray& OutLifetimeProps) const { Super::GetLifetimeReplicatedProps(OutLifetimeProps); DOREPLIFETIME(AExampleActor, ServerAuthorityValue); DOREPLIFETIME(AExampleActor, Score); } void AExampleActor::OnRep_Score() { UE_LOG(LogTemp, Log, TEXT("Score replicated: %d"), Score); } ``` -------------------------------- ### Unreal Engine HTTP Request Example Usage in C++ Source: https://github.com/mrrobinofficial/guide-unrealengine/blob/main/README.md This C++ code provides an example of how to call the `SendRequest` function to make an HTTP GET request in Unreal Engine. It demonstrates defining base and endpoint URLs, setting up a delegate for the callback, and logging the response. This function is intended to be called from within an Unreal Engine project. ```cpp void YourClass::SendTestRequest() { // Final URL: BASE_URL + ENDPOINT_URL = "https://swapi.dev/api/planets/3/" // Helpful to split the endpoint, as you can switch to another endpoint. const FString BASE_URL = "https://swapi.dev/api/"; const FString ENDPOINT_URL = "planets/3/"; // "starships/9/", "people/1/" FString JSON; FHTTPRequest Delegate; Delegate.BindDynamic(this, &YourClass::OnRequestCompleted); // Send the request with delegate passed into the parameters SendRequest(BASE_URL, ENDPOINT_URL, EHTTPRequestType::GET, "", Delegate); } void YourClass::OnRequestCompleted(const FString& Result, bool bWasSuccessful) { if (!bWasSuccessful) { UE_LOGFMT(LogTemp, Log, "The Request was not successful!"); return; } UE_LOGFMT(LogTemp, Log, "Request Output: {0}", Result); } ``` -------------------------------- ### Demonstrate C++ Variable Initialization and Brace-Initializer Narrowing Source: https://github.com/mrrobinofficial/guide-unrealengine/blob/main/sections/constructors.md No description ```C++ // Initialization using assignment statement\nint num1 = 10;\n\n// Initialization using brace initializer\nint num2{20};\n\nint num3 = 1000; // OK, no narrowing conversion\nint num4 = 1000.5; // OK, narrowing conversion from double to int\nint num5{1000.5}; // Error, narrowing conversion from double to int ``` -------------------------------- ### Unreal Engine Character Types (C++) Source: https://context7.com/mrrobinofficial/guide-unrealengine/llms.txt Shows platform-independent character types including TCHAR, ANSICHAR, WIDECHAR, and UTF8CHAR with example assignments. ```cpp TCHAR MyChar = 'A'; ANSICHAR AnsiChar = 'B'; WIDECHAR WideChar = L'C'; UTF8CHAR Utf8Char = u8'D'; ``` -------------------------------- ### Unreal Engine TMap Declaration and Initialization Source: https://github.com/mrrobinofficial/guide-unrealengine/blob/main/sections/data_types.md Demonstrates how to include the necessary header and declare a TMap with specified key and value types, initializing it with sample data. ```cpp #include "Containers/Map.h" TMap MyMap = { { TEXT("player_id"), 457865 }, { TEXT("player_age"), 35 } }; // MyMap: { { "player_id", 457865 }, { "player_age", 35 } } ``` -------------------------------- ### UPROPERTY EditFixedSize Example Source: https://github.com/mrrobinofficial/guide-unrealengine/blob/main/sections/unreal_header_tool.md Shows using EditFixedSize to allow editing of TArray and TMap size. This prevents adding or removing elements. ```cpp UPROPERTY(EditAnywhere, EditFixedSize) TArray Usernames = { TEXT("JohnDoe"), TEXT("MrRobin"), TEXT("JaneDoe") }; ``` -------------------------------- ### Implement StartSession Function for Analytics Library in C++ Source: https://github.com/mrrobinofficial/guide-unrealengine/blob/main/backups/README_2023_12_10.md Provides the C++ implementation for the `StartSession` function within the `UAnalyticsBlueprintLibrary`. This function attempts to get the default analytics provider and calls its `StartSession` method, logging a warning if the provider is invalid. ```cpp #include "AnalyticsBlueprintLibrary.h" #include "Analytics/AnalyticsComponent.h" #include "Interfaces/IAnalyticsProvider.h" // Assuming UE_LOG and other necessary headers are included // DEFINE_LOG_CATEGORY_STATIC(LogAnalyticsBPLib, Log, All); bool UAnalyticsBlueprintLibrary::StartSession() { TSharedPtr Provider = FAnalytics::Get().GetDefaultConfiguredProvider(); if (Provider.IsValid()) return Provider->StartSession(); else { UE_LOG( LogAnalyticsBPLib, Warning, TEXT("StartSession: Failed to get the default analytics provider. Double check your [Analytics] configuration in your INI") ); } return false; } ``` -------------------------------- ### FBox and FBox2D Initialization in C++ Source: https://github.com/mrrobinofficial/guide-unrealengine/blob/main/README.md Shows how to initialize 3D and 2D bounding box structs using min and max points. Use FBox3f/FBox2f for float precision and FBox3d/FBox2d for double precision. ```cpp FVector MinPoint = FVector(15.5f, 15.5f); FVector MaxPoint = FVector(25.0f, 25.0f); FBox Box2D = FBox(MinPoint, MaxPoint); ``` ```cpp FVector2D MinPoint = FVector2D(10, 10); FVector2D MaxPoint = FVector2D(20, 20); FBox2D Box2D = FBox2D(MinPoint, MaxPoint); ``` -------------------------------- ### Initialize FVector4 with predefined values (C++) Source: https://github.com/mrrobinofficial/guide-unrealengine/blob/main/sections/data_types.md Illustrates initializing FVector4 with predefined values like ZeroVector and OneVector. Useful for default vector setups. ```cpp FVector4 OldLocation = FVector4::ZeroVector; // (0, 0, 0) FVector4 NewLocation = FVector4::OneVector; // (1, 1, 1) ``` -------------------------------- ### Unreal Engine Math Types (C++) Source: https://context7.com/mrrobinofficial/guide-unrealengine/llms.txt Examples of common math types including FVector, FRotator, FTransform with vector operations like normalization and distance calculation. ```cpp FVector Location(100.0f, 200.0f, 300.0f); FRotator Rotation(0.0f, 90.0f, 0.0f); FTransform Transform(Rotation, Location); FVector Direction = FVector::ForwardVector; float Distance = FVector::Distance(Location, FVector::ZeroVector); FVector Normalized = Direction.GetSafeNormal(); ``` -------------------------------- ### AddOnScreenDebugMessage Example Source: https://github.com/mrrobinofficial/guide-unrealengine/blob/main/sections/logging.md Displays a static message directly on the game screen using the GEngine->AddOnScreenDebugMessage function. This function allows specifying display duration, color, and the message content. ```cpp /* void AddOnScreenDebugMessage ( uint64 Key, // A unique key to prevent the same message from being added multiple times. float TimeToDisplay, // How long to display the message, in seconds. FColor DisplayColor, // The color to display the text in. const FString & DebugMessage, // The message to display. bool bNewerOnTop, const FVector2D & TextScale ) Add a FString to the On-screen debug message system. bNewerOnTop only works with Key == INDEX_NONE This function will add a debug message to the onscreen message list. It will be displayed for FrameCount frames. */ GEngine->AddOnScreenDebugMessage(-1, 5.0f, FColor::White, TEXT("This message will appear on the screen!")); ``` -------------------------------- ### Unreal Engine TMap: Get Number of Elements Source: https://github.com/mrrobinofficial/guide-unrealengine/blob/main/sections/data_types.md Demonstrates how to obtain the total count of key-value pairs currently stored within a TMap using the Num() function. ```cpp int32 NumOfElements = MyMap.Num(); // 4 ``` -------------------------------- ### Implement StartSession for Analytics Library (C++) Source: https://github.com/mrrobinofficial/guide-unrealengine/blob/main/README.md Implements the StartSession function for the Analytics Blueprint Function Library. It retrieves the default analytics provider and calls its StartSession method. If the provider is invalid, it logs a warning. This function returns a boolean indicating success or failure. ```cpp bool UAnalyticsBlueprintLibrary::StartSession() { TSharedPtr Provider = FAnalytics::Get().GetDefaultConfiguredProvider(); if (Provider.IsValid()) return Provider->StartSession(); else { UE_LOG( LogAnalyticsBPLib, Warning, TEXT("StartSession: Failed to get the default analytics provider. Double check your [Analytics] configuration in your INI") ); } return false; } ``` -------------------------------- ### C++ Switch Statement - Basic Syntax and Execution Flow Source: https://github.com/mrrobinofficial/guide-unrealengine/blob/main/README_CPP.md Demonstrates the fundamental syntax of C++ switch statements for multi-way branching based on expression values. Shows how to handle multiple cases with break statements and optional default case for unmatched values. ```cpp switch (expression) { case value1: // Code to be executed if expression matches value1 break; case value2: // Code to be executed if expression matches value2 break; // Add more case statements as needed default: // Code to be executed if none of the cases match break; } ``` -------------------------------- ### Unreal Engine Container Types (C++) Source: https://context7.com/mrrobinofficial/guide-unrealengine/llms.txt Usage examples for Unreal's container types including TArray (dynamic array), TMap (dictionary), and TSet (unique elements) with common operations. ```cpp TArray DynamicArray = {1, 2, 3, 4, 5}; DynamicArray.Add(6); DynamicArray.Remove(3); int32 Count = DynamicArray.Num(); TMap Dictionary; Dictionary.Add(TEXT("Health"), 100); Dictionary.Add(TEXT("Mana"), 50); int32 Health = Dictionary.FindRef(TEXT("Health")); TSet UniqueItems; UniqueItems.Add(TEXT("Sword")); UniqueItems.Add(TEXT("Shield")); bool bHasSword = UniqueItems.Contains(TEXT("Sword")); ``` -------------------------------- ### Unreal Engine TMap: Try Getting Value by Key Source: https://github.com/mrrobinofficial/guide-unrealengine/blob/main/sections/data_types.md Demonstrates the TryGetValue function, which attempts to retrieve the value associated with a specific key and returns true if successful, outputting the value to a reference. ```cpp int32 OutSpeed; if (MyMap.TryGetValue(TEXT("player_speed"), OutSpeed)) { UE_LOG(LogTemp, Log, TEXT("Player's speed: %i [m/s]"), OutSpeed); } ``` -------------------------------- ### Localize Text with LOCTEXT and NSLOCTEXT (C++) Source: https://github.com/mrrobinofficial/guide-unrealengine/blob/main/sections/data_types.md Provides examples of using `LOCTEXT` and `NSLOCTEXT` macros to create localized text literals in C++. It also demonstrates defining and undefining a namespace for localization. ```cpp #define LOCTEXT_NAMESPACE "MyNamespace" // Create text literals FText PlayGameText = LOCTEXT("PlayGame", "Spiel beginnen"); // German langauge // Helpful in the editor to localize the text into another language. FText QuitGameText = NSLOCTEXT("StartMenu", "QuitGame", "Avsluta spelet"); // Swedish language #undef LOCTEXT_NAMESPACE // Undefine the current namespace ``` -------------------------------- ### Demonstrate Value vs Reference Types in C++ Source: https://github.com/mrrobinofficial/guide-unrealengine/blob/main/backups/README_2023_12_10.md Provides a comprehensive example comparing value copies and reference bindings using a custom struct. Includes dynamic allocation, pointer manipulation, and proper cleanup. Highlights how modifications through references and pointers affect the original object. ```cpp #include #include struct Coords // Test struct and class { public: Coords(int x, int y) : X(x) , Y(y) {} public: int X; int Y; public: std::string toString() const { return \"(\" + std::to_string(X) + ", " + std::to_string(Y) + \")\"; } }; int main() { Coords A(1, 2); Coords& B = A; // Test value type and reference type Coords* C = &B; Coords* D = new Coords(5, 10 Coords* E = &(*C); // Or &*C; B.X = 69; C->Y = 1337; D->Y = D->Y * 2; E = &*D; E->X = 10; std::cout << A.toString() << std::endl; std::cout << B.toString() << std::endl; std::cout << C->toString() << std::endl; std::cout << D->toString() << std::endl; std::cout << E->toString() << std::endl; delete D; // Remember: Delete raw pointers return 0; } ``` -------------------------------- ### Unreal Engine USTRUCT Declaration Source: https://github.com/mrrobinofficial/guide-unrealengine/blob/main/sections/unreal_header_tool.md Provides an example of declaring a USTRUCT in Unreal Engine, intended for use within UCLASSes and exposure to Blueprints. Properties within the struct are declared using UPROPERTY. ```cpp USTRUCT(BlueprintType) struct FMyStruct { GENERATED_BODY() UPROPERTY(BlueprintReadWrite, Category = "MyStruct") int32 Value1; UPROPERTY(BlueprintReadWrite, Category = "MyStruct") FString Value2; }; ``` -------------------------------- ### C++ Unreal Engine HTTP Request Setup Source: https://github.com/mrrobinofficial/guide-unrealengine/blob/main/README.md Defines the necessary headers and an enum for HTTP request types in Unreal Engine. It also declares a delegate for handling asynchronous HTTP responses and a function to initiate these requests. ```cpp #include "HttpModule.h" #include "Interfaces/IHttpResponse.h" #include "PlatformHttp.h" #include "JsonObjectConverter.h" // Include this, if you want to send some JSON data into the request UENUM(BlueprintType) enum class EHTTPRequestType : uint8 { GET, POST, PUT, DELETE }; // Delegate for the callback DECLARE_DYNAMIC_DELEGATE_ThreeParams(FHTTPRequest, const FString&, Result, int32 ResponseCode, bool, bWasSuccessful); UFUNCTION(BlueprintCallable, Category = "MyPawn") /** * Send a request via HTTP protocol system. * * @param BaseURL - Base URL on which to process the request on. * @param EndpointURL - Endpoint URL. Combined with base URL to get fully qualified URL for the request. * @param RequestType - What type of request (GET, POST, PUT, DELETE) * @param Callback - Callback of the request * @return A boolean, if the request was successfully sent out. */ bool SendRequest( const FString BaseURL, const FString EndpointURL, const EHTTPRequestType RequestType, FString Payload, FHTTPRequest Callback ); ``` -------------------------------- ### Initialize FIntRect and FUintRect in C++ Source: https://github.com/mrrobinofficial/guide-unrealengine/blob/main/sections/data_types.md Demonstrates the declaration and initialization of 2D integer rectangles (FIntRect and FUintRect) in C++. Rectangles are defined by their minimum and maximum points, with examples showing initialization for both signed and unsigned integer ranges. ```cpp FIntPoint MinPoint = FIntPoint(-127, -127); FIntPoint MaxPoint = FIntPoint(128, 128); FIntRect Rect = FIntRect(MinPoint, MaxPoint); FUIntPoint UnsignedMinPoint = FUIntPoint(0, 0); FUIntPoint UnsignedMaxPoint = FUIntPoint(255, 255); FUIntRect UnsignedRect = FIntRect(UnsignedMinPoint, UnsignedMaxPoint); ```