### Actor Construction Script Example Source: https://github.com/hazelight/docs-unrealengine-angelscript/blob/master/content/scripting/actors-components.md Override the ConstructionScript() event to add components to an actor during its construction. This example demonstrates spawning a variable number of static meshes based on the SpawnMeshCount property. ```cpp class AExampleActor : AActor { // How many meshes to place on the actor UPROPERTY() int SpawnMeshCount = 5; // Which static mesh to place UPROPERTY() UStaticMesh MeshAsset; UFUNCTION(BlueprintOverride) void ConstructionScript() { Print(f"Spawning {SpawnMeshCount} meshes from construction script!"); for (int i = 0; i < SpawnMeshCount; ++i) { // Construct a new static mesh on this actor UStaticMeshComponent MeshComp = UStaticMeshComponent::Create(this); // Set the mesh we wanted for it MeshComp.SetStaticMesh(MeshAsset); } } ``` -------------------------------- ### Before Function for Script Tests Source: https://github.com/hazelight/docs-unrealengine-angelscript/blob/master/content/scripting/script-tests.md The Before function runs at the start of a test's lifetime. It's used for setup, such as initializing game mode and save systems, and loading a specific save file without a full map reload. ```cpp float CashFromV1Save = 12345.0; // manually create a save in the previous version to use in the test here. FString V1SaveFileName = "IntegrationTest_UpgradeSaveGameV1"; // This runs at the start of this command's lifetime in the test. GetWorld(), and // therefore all the automatic context places it's used, should be valid here // (unless you try changing the map) UFUNCTION(BlueprintOverride) void Before() { auto GM = ExampleGameMode::Get(); auto ExampleSaveSystem = UExampleSaveSystem::Get(); ExampleSaveSystem.SelectSaveFile(V1SaveFileName); // can't change the map in an integration test, so don't do a full map reload. Just deserialize ExampleSaveSystem.LoadWithoutReload(V1SaveFileName); } ``` -------------------------------- ### Install Unreal Engine Angelscript Source: https://context7.com/hazelight/docs-unrealengine-angelscript/llms.txt Follow these steps to install the custom Unreal Engine fork and the VS Code extension for Angelscript. ```sh # 1. Get Unreal Engine source access: # https://www.unrealengine.com/en-US/ue-on-github # 2. Clone and build the Angelscript engine fork: git clone https://github.com/Hazelight/UnrealEngine-Angelscript # 3. Install the VS Code extension: # Search "Unreal Angelscript" in the VS Code Extensions marketplace # or visit: https://marketplace.visualstudio.com/items?itemName=Hazelight.unreal-angelscript # 4. Open your project in the custom editor. The Script/ folder is created automatically. # Open it in VS Code via: Tools > Open Angelscript Workspace ``` -------------------------------- ### Define and Use Local Player Subsystem Source: https://github.com/hazelight/docs-unrealengine-angelscript/blob/master/content/scripting/subsystems.md Define a custom local player subsystem and retrieve an instance of it using a ULocalPlayer object. Ensure the ULocalPlayer is correctly obtained, for example, from a player controller. ```cpp class UMyPlayerSubsystem : UScriptLocalPlayerSubsystem {}; void UseScriptedPlayerSubsystem() { ULocalPlayer RelevantPlayer = Gameplay::GetPlayerController(0).LocalPlayer; auto MySubsystem = UMyPlayerSubsystem::Get(RelevantPlayer); } ``` -------------------------------- ### Set Timer Example Source: https://github.com/hazelight/docs-unrealengine-angelscript/blob/master/content/scripting/function-libraries.md Demonstrates how to set a timer to execute a function after a specified delay. The timer is set using the System::SetTimer() function, which takes the object, function name, delay in seconds, and a boolean for looping as arguments. ```AngelScript class ATimerExample : AActor { UFUNCTION(BlueprintOverride) void BeginPlay() { // Execute this.OnTimerExecuted() after 2 seconds System::SetTimer(this, "OnTimerExecuted", 2.0, bLooping = false); } UFUNCTION() private void OnTimerExecuted() { Print("Timer executed!"); } } ``` -------------------------------- ### Example Script Test Source: https://github.com/hazelight/docs-unrealengine-angelscript/blob/master/content/scripting/script-tests.md This snippet demonstrates a basic script test structure, including assertions for comparing expected and actual values. It's useful for verifying script logic and data integrity. ```angelscript void Test_CashValues() { // Assert that the cash values match the expected outcome. Assert(Expected cash: {CashFromV1Save}, Actual cash: {ActualCash} (-1 is null)); } ``` -------------------------------- ### Example Usage of a Struct Mixin Method Source: https://github.com/hazelight/docs-unrealengine-angelscript/blob/master/content/scripting/mixin-methods.md Demonstrates how to call a mixin method `SetVectorToZero` on a local `FVector` variable. This shows the practical application of mixin methods to modify struct members. ```angelscript void Example_StructMixin() { FVector LocalValue; LocalValue.SetVectorToZero(); } ``` -------------------------------- ### Implementing Property Accessor Functions Source: https://context7.com/hazelight/docs-unrealengine-angelscript/llms.txt Use the 'property' keyword on getter and setter methods to allow them to be accessed like properties. This example demonstrates clamping health and triggering an OnDeath event. ```angelscript class APlayerCharacter : ACharacter { private float HealthInternal = 100.0; // Getter used as property: character.Health reads this float GetHealth() const property { return HealthInternal; } // Setter used as property: character.Health = x calls this void SetHealth(float NewHealth) property { HealthInternal = Math::Clamp(NewHealth, 0.0, 100.0); if (HealthInternal <= 0.0) OnDeath(); } UFUNCTION(BlueprintOverride) void BeginPlay() { // Reads via GetHealth() Print(f"Starting health: {Health}"); // Writes via SetHealth() Health = 75.0; Print(f"After damage: {Health}"); } void OnDeath() { Print("Player died!"); } } ``` -------------------------------- ### Get and Use Level Editor Subsystem Source: https://github.com/hazelight/docs-unrealengine-angelscript/blob/master/content/scripting/subsystems.md Retrieve the Level Editor Subsystem singleton and use its NewLevel function to create a new level. Note that many subsystems are Editor-only and cannot be used in packaged games. ```cpp void TestCreateNewLevel() { auto LevelEditorSubsystem = ULevelEditorSubsystem::Get(); LevelEditorSubsystem.NewLevel("/Game/NewLevel"); } ``` -------------------------------- ### Declare and Use an Event with Multiple Handlers Source: https://github.com/hazelight/docs-unrealengine-angelscript/blob/master/content/scripting/delegates.md Declare an event using the 'event' keyword. Attach multiple functions to the event using 'AddUFunction()' and then broadcast the event to trigger all attached functions. This example demonstrates adding two handlers to an event. ```angelscript event void FExampleEvent(int Counter); class AEventExample : AActor { UPROPERTY() FExampleEvent OnExampleEvent; private int CallCounter = 0; UFUNCTION(BlueprintOverride) void BeginPlay() { // Add two functions to be called when the event is broadcast OnExampleEvent.AddUFunction(this, "FirstHandler"); OnExampleEvent.AddUFunction(this, "SecondHandler"); } UFUNCTION() private void FirstHandler(int Counter) { Print("Called first handler"); } UFUNCTION() private void SecondHandler(int Counter) { Print("Called second handler"); } } ``` -------------------------------- ### Angelscript Unit Test Example Source: https://github.com/hazelight/docs-unrealengine-angelscript/blob/master/content/scripting/script-tests.md Demonstrates basic assertions within an Angelscript unit test function. Use AssertTrue, AssertEquals, and AssertNotNull for test validation. ```angelscript void Test_NameOfTheTestCase(FUnitTest& T) { // Fails the test. T.AssertTrue(false); T.AssertEquals(1, 1 + 1); T.AssertNotNull(nullptr); } ``` -------------------------------- ### Define Property Accessor in AngelScript Source: https://github.com/hazelight/docs-unrealengine-angelscript/blob/master/content/scripting/properties-and-accessors.md Use the `property` keyword with `Get..()` methods to allow them to be accessed as properties. The `BeginPlay` function demonstrates calling this property. ```angelscript class AExampleActor : AActor { // The `property` keyword lets this function be used as a property instead FVector GetRotatedOffset() const property { return ActorRotation.RotateVector(FVector(0.0, 1.0, 1.0)); } UFUNCTION(BlueprintOverride) void BeginPlay() { // This automatically calls GetRotatedOffset() when used as a property Print("Offset at BeginPlay: "+RotatedOffset); } } ``` -------------------------------- ### Implement Actor Countdown Timer in AngelScript Source: https://github.com/hazelight/docs-unrealengine-angelscript/blob/master/content/getting-started/introduction.md Defines an actor with a configurable countdown timer. The timer starts on BeginPlay and decrements each tick. Use this to add time-based logic to actors. ```angelscript class AIntroductionActor : AActor { UPROPERTY() float CountdownDuration = 5.0; float CurrentTimer = 0.0; bool bCountdownActive = false; UFUNCTION(BlueprintOverride) void BeginPlay() { // Start the countdown on beginplay with the configured duration CurrentTimer = CountdownDuration; bCountdownActive = true; } UFUNCTION(BlueprintOverride) void Tick(float DeltaSeconds) { if (bCountdownActive) { // Count down the timer CurrentTimer -= DeltaSeconds; if (CurrentTimer <= 0.0) { ``` -------------------------------- ### Retrieve or Create Components on an Actor Source: https://github.com/hazelight/docs-unrealengine-angelscript/blob/master/content/scripting/actors-components.md Use `UMyComponentClass::GetOrCreate()` to get an existing component of a specific type, or create a new one if it doesn't exist. This can also be used to create a component with a specific name. ```angelscript // Find our own interaction handling component on the actor. // If it does not exist, create it. UInteractionComponent InteractComp = UInteractionComponent::GetOrCreate(Actor); // Find an interaction handling component specifically named "ClimbingInteraction", // or create a new one with that name auto ClimbComp = UInteractionComponent::GetOrCreate(Actor, "ClimbingInteraction"); ``` -------------------------------- ### Generated Integration Test Cases Source: https://github.com/hazelight/docs-unrealengine-angelscript/blob/master/content/scripting/script-tests.md When running complex integration tests, especially those involving parameterized data like different potions, the test runner can generate multiple specific test cases. This example shows how a test named `ComplexIntegrationTest_PotionsAreTooStrongForKnight` can be automatically expanded into individual tests for each potion variant (e.g., `DA_Potion1`, `DA_Potion2`, `DA_Potion3`). ```text Angelscript.IntegrationTest.Your.Path.ComplexIntegrationTest_PotionsAreTooStrongForKnight[DA_Potion1] Angelscript.IntegrationTest.Your.Path.ComplexIntegrationTest_PotionsAreTooStrongForKnight[DA_Potion2] Angelscript.IntegrationTest.Your.Path.ComplexIntegrationTest_PotionsAreTooStrongForKnight[DA_Potion3] ``` -------------------------------- ### Subsystems Source: https://context7.com/hazelight/docs-unrealengine-angelscript/llms.txt Access and create Unreal subsystems (singletons) using typed `::Get()` static methods for managing game state and editor functionality. ```APIDOC ## Subsystems Access and create Unreal subsystems (singletons) using typed `::Get()` static methods. ```angelscript // Using a built-in editor subsystem void OpenNewLevel() { auto LevelSubsystem = ULevelEditorSubsystem::Get(); LevelSubsystem.NewLevel("/Game/Maps/NewLevel"); } // Creating a custom world subsystem class UGameFlowSubsystem : UScriptWorldSubsystem { private int RoundNumber = 0; UFUNCTION(BlueprintOverride) void Initialize() { Print("GameFlow subsystem initialized!"); } UFUNCTION(BlueprintOverride) void Tick(float DeltaTime) { // Runs every world tick } UFUNCTION() void StartNewRound() { RoundNumber++; Print(f"Round {RoundNumber} started!"); } UFUNCTION() int GetCurrentRound() const { return RoundNumber; } } // Accessing the custom subsystem from anywhere void Example_UseSubsystem() { auto FlowSys = UGameFlowSubsystem::Get(); FlowSys.StartNewRound(); Print(f"Currently on round {FlowSys.GetCurrentRound()}"); } // Local player subsystem usage class UInventorySubsystem : UScriptLocalPlayerSubsystem {} void Example_PlayerSubsystem() { ULocalPlayer Player = Gameplay::GetPlayerController(0).LocalPlayer; auto InvSys = UInventorySubsystem::Get(Player); } ``` ``` -------------------------------- ### Using Built-in and Custom Subsystems in AngelScript Source: https://context7.com/hazelight/docs-unrealengine-angelscript/llms.txt Explains how to access Unreal Engine's subsystem architecture, including using static `::Get()` methods for built-in editor and world subsystems, and how to create and use custom `UScriptWorldSubsystem` and `UScriptLocalPlayerSubsystem` classes. ```angelscript // Using a built-in editor subsystem void OpenNewLevel() { auto LevelSubsystem = ULevelEditorSubsystem::Get(); LevelSubsystem.NewLevel("/Game/Maps/NewLevel"); } // Creating a custom world subsystem class UGameFlowSubsystem : UScriptWorldSubsystem { private int RoundNumber = 0; UFUNCTION(BlueprintOverride) void Initialize() { Print("GameFlow subsystem initialized!"); } UFUNCTION(BlueprintOverride) void Tick(float DeltaTime) { // Runs every world tick } UFUNCTION() void StartNewRound() { RoundNumber++; Print(f"Round {RoundNumber} started!"); } UFUNCTION() int GetCurrentRound() const { return RoundNumber; } } // Accessing the custom subsystem from anywhere void Example_UseSubsystem() { auto FlowSys = UGameFlowSubsystem::Get(); FlowSys.StartNewRound(); Print(f"Currently on round {FlowSys.GetCurrentRound()}"); } // Local player subsystem usage class UInventorySubsystem : UScriptLocalPlayerSubsystem {} void Example_PlayerSubsystem() { ULocalPlayer Player = Gameplay::GetPlayerController(0).LocalPlayer; auto InvSys = UInventorySubsystem::Get(Player); } ``` -------------------------------- ### Modify Actor for Blueprint Interaction Source: https://github.com/hazelight/docs-unrealengine-angelscript/blob/master/content/getting-started/introduction.md Adjusts the actor's BeginPlay and Tick functions to enable interaction with Blueprints. The countdown is no longer started automatically on BeginPlay and requires an external call to start. ```as UFUNCTION(BlueprintOverride) void BeginPlay() { // We no longer start the countdown on BeginPlay automatically } ``` ```as UFUNCTION() void StartCountdown() { // Start the countdown when StartCountdown() is called CurrentTimer = CountdownDuration; bCountdownActive = true; } ``` ```as /** * Declare an overridable event so the actor blueprint can * respond when the countdown finishes */ UFUNCTION(BlueprintEvent) void FinishedCountdown() {} ``` ```as UFUNCTION(BlueprintOverride) void Tick(float DeltaSeconds) { if (bCountdownActive) { // Count down the timer CurrentTimer -= DeltaSeconds; ``` -------------------------------- ### Function Libraries (Namespaced Globals) Source: https://context7.com/hazelight/docs-unrealengine-angelscript/llms.txt Access Unreal's Blueprint function libraries through simplified namespace syntax like System::, Math::, Gameplay::, and Niagara::. ```APIDOC ## Function Libraries (Namespaced Globals) Access Unreal's Blueprint function libraries through simplified namespace syntax. ```angelscript class ATimerExample : AActor { UFUNCTION(BlueprintOverride) void BeginPlay() { // System:: wraps UKismetSystemLibrary System::SetTimer(this, n"OnTimerFired", 2.0, bLooping = false); // Math:: wraps FMath (not UKismetMathLibrary) float RandomVal = Math::RandRange(0.0, 100.0); FVector Clamped = Math::Clamp(FVector(5.0, -10.0, 200.0), FVector(-50.0), FVector(50.0)); // Gameplay:: wraps UGameplayStatics APlayerController PC = Gameplay::GetPlayerController(0); Print(f"Player at: {PC.Pawn.ActorLocation}"); // System:: draw debug helpers System::DrawDebugSphere(GetActorLocation(), 100.0, 12, FLinearColor::Red, false, 5.0); // Niagara:: for particle systems // Niagara::SpawnSystemAtLocation(MyNiagaraSystem, GetActorLocation()); } UFUNCTION() private void OnTimerFired() { Print("Timer fired after 2 seconds!"); } } ``` ``` -------------------------------- ### Declare an Editable Integer Property Source: https://github.com/hazelight/docs-unrealengine-angelscript/blob/master/content/scripting/properties-and-accessors.md Use the 'editable' keyword to expose a property to the editor. This example shows how to declare an integer property named 'VisibleProperty'. ```angelscript class MyClass { editable int VisibleProperty; } ``` -------------------------------- ### Declare Script-Only Functions Source: https://github.com/hazelight/docs-unrealengine-angelscript/blob/master/content/scripting/functions-and-events.md Define methods within a class or global functions that are only accessible from script. The example shows a class method calling a global function. ```angelscript class AExampleActor : AActor { void MyMethod() { MyGlobalFunction(this); } } void MyGlobalFunction(AActor Actor) { if (!Actor.IsHidden()) { Actor.DestroyActor(); } } ``` -------------------------------- ### Bind and Execute Delegate Source: https://github.com/hazelight/docs-unrealengine-angelscript/blob/master/content/scripting/delegates.md Demonstrates how to declare a delegate variable within a class, bind a function to it using BindUFunction, and execute the delegate. This is useful for creating callbacks or event handlers. ```angelscript class ADelegateExample : AActor { FExampleDelegate StoredDelegate; UFUNCTION(BlueprintOverride) void BeginPlay() { // Bind the delegate so executing it calls this.OnDelegateExecuted() StoredDelegate.BindUFunction(this, "OnDelegateExecuted"); // You can also create new bound delegates by using the constructor: StoredDelegate = FExampleDelegateSignature(this, "OnDelegateExecuted"); } UFUNCTION() private void OnDelegateExecuted(UObject Object, float Value) { Print(f"Delegate was executed with object {Object} and v ``` -------------------------------- ### Simulate Buying Potion and Expect Response Source: https://github.com/hazelight/docs-unrealengine-angelscript/blob/master/content/scripting/script-tests.md This snippet demonstrates a complex integration test scenario. It simulates a Knight buying a potion from a PotionSeller and then uses `AddLatentAutomationCommand` with `UExpectResponse` to verify the seller's dialogue. This is useful for testing conversational AI or scripted NPC interactions. ```AngelScript Knight.BuyPotionFrom(PotionSeller, Potion); T.AddLatentAutomationCommand(UExpectResponse("My potions are too strong for you traveller.", Knight, PotionSeller)); ``` -------------------------------- ### Get Components by Class on an Actor Source: https://github.com/hazelight/docs-unrealengine-angelscript/blob/master/content/scripting/actors-components.md Use `Actor.GetComponentsByClass()` to retrieve all components of a specified type attached to an actor. The component type is inferred from the array passed as an argument. ```angelscript AActor Actor; TArray StaticMeshComponents; Actor.GetComponentsByClass(StaticMeshComponents); for (UStaticMeshComponent MeshComp : StaticMeshComponents) { Print(f"Static Mesh Component: {MeshComp.Name}"); } ``` -------------------------------- ### Formatted String with Float Precision Source: https://github.com/hazelight/docs-unrealengine-angelscript/blob/master/content/scripting/format-strings.md Control the precision of floating-point numbers in formatted strings using format specifiers. For example, `:.3` formats a float to three decimal places. ```angelscript Print(f"Three Decimals: {ActorLocation.Z :.3}"); ``` -------------------------------- ### Get All Actors of a Specific Class Source: https://github.com/hazelight/docs-unrealengine-angelscript/blob/master/content/scripting/actors-components.md Use the global function `GetAllActorsOfClass()` to find all actors of a particular type currently present in the world. The actor type is determined by the array provided. ```angelscript // Find all niagara actors currently in the level TArray NiagaraActors; GetAllActorsOfClass(NiagaraActors); ``` -------------------------------- ### Accessing Blueprint Function Libraries with Namespaces in AngelScript Source: https://context7.com/hazelight/docs-unrealengine-angelscript/llms.txt Demonstrates using simplified namespace syntax to access Unreal's Blueprint function libraries like UKismetSystemLibrary, FMath, and UGameplayStatics. Ensure the relevant libraries are available in your AngelScript environment. ```angelscript class ATimerExample : AActor { UFUNCTION(BlueprintOverride) void BeginPlay() { // System:: wraps UKismetSystemLibrary System::SetTimer(this, n"OnTimerFired", 2.0, bLooping = false); // Math:: wraps FMath (not UKismetMathLibrary) float RandomVal = Math::RandRange(0.0, 100.0); FVector Clamped = Math::Clamp(FVector(5.0, -10.0, 200.0), FVector(-50.0), FVector(50.0)); // Gameplay:: wraps UGameplayStatics APlayerController PC = Gameplay::GetPlayerController(0); Print(f"Player at: {PC.Pawn.ActorLocation}"); // System:: draw debug helpers System::DrawDebugSphere(GetActorLocation(), 100.0, 12, FLinearColor::Red, false, 5.0); // Niagara:: for particle systems // Niagara::SpawnSystemAtLocation(MyNiagaraSystem, GetActorLocation()); } UFUNCTION() private void OnTimerFired() { Print("Timer fired after 2 seconds!"); } } ``` -------------------------------- ### Create a Scripted World Subsystem Source: https://github.com/hazelight/docs-unrealengine-angelscript/blob/master/content/scripting/subsystems.md Inherit from UScriptWorldSubsystem to create a world-scoped subsystem. Expose functions using UFUNCTION for Blueprint access. Initialize and Tick functions are automatically called. ```cpp class UMyGameWorldSubsystem : UScriptWorldSubsystem { UFUNCTION(BlueprintOverride) void Initialize() { Print("MyGame World Subsystem Initialized!"); } UFUNCTION(BlueprintOverride) void Tick(float DeltaTime) { Print("Tick"); } // Create functions on the subsystem to expose functionality UFUNCTION() void LookAtMyActor(AActor Actor) { } } void UseMyGameWorldSubsystem() { auto MySubsystem = UMyGameWorldSubsystem::Get(); MySubsystem.LookAtMyActor(nullptr); } ``` -------------------------------- ### Run Unit Tests from Command Line Source: https://context7.com/hazelight/docs-unrealengine-angelscript/llms.txt Execute all Angelscript unit tests using the Unreal Editor command-line tool. Ensure to replace `MyProject.uproject` with your project's name. The `-as-exit-on-error` flag is useful for CI/CD pipelines. ```sh # Run all unit tests from command line: Engine\Binaries\Win64\UnrealEditor-Cmd.exe "MyProject.uproject" \ -NullRHI -NoSound -NoSplash \ -ExecCmds="Automation RunTests Angelscript.UnitTests" \ -TestExit "Automation Test Queue Empty" \ -unattended -stdout -as-exit-on-error ``` -------------------------------- ### Create and Attach a New Component Source: https://github.com/hazelight/docs-unrealengine-angelscript/blob/master/content/scripting/actors-components.md Use UStaticMeshComponent::Create() to create a new component and AttachToComponent() to attach it to a parent actor. Component names are optional and will be auto-generated if not provided. ```angelscript ACharacter Character; // Create a new static mesh component on the character and attach it to the character mesh UStaticMeshComponent NewComponent = UStaticMeshComponent::Create(Character); NewComponent.AttachToComponent(Character.Mesh); ``` -------------------------------- ### Implementing Multicast Events (Event Dispatchers) Source: https://context7.com/hazelight/docs-unrealengine-angelscript/llms.txt Declare multicast events with the 'event' keyword and use UPROPERTY to expose them as Event Dispatchers in Blueprint. Multiple functions can be bound and broadcast. ```angelscript // Declare event type in global scope event void FOnScoreChanged(int NewScore, int OldScore); class AScoreManager : AActor { // UPROPERTY makes the event visible in Blueprint as an Event Dispatcher UPROPERTY() FOnScoreChanged OnScoreChanged; private int Score = 0; UFUNCTION() void AddScore(int Points) { int OldScore = Score; Score += Points; // Broadcast to all bound listeners OnScoreChanged.Broadcast(Score, OldScore); } } class AScoreUI : AActor { UFUNCTION(BlueprintOverride) void BeginPlay() { // Find the score manager and subscribe TArray Managers; GetAllActorsOfClass(Managers); if (Managers.Num() > 0) { Managers[0].OnScoreChanged.AddUFunction(this, n"OnScoreUpdated"); } } UFUNCTION() private void OnScoreUpdated(int NewScore, int OldScore) { Print(f"Score changed: {OldScore} -> {NewScore}"); } } ``` -------------------------------- ### Run Angelscript Unit Tests from Command Line Source: https://github.com/hazelight/docs-unrealengine-angelscript/blob/master/content/scripting/script-tests.md Executes Angelscript unit tests using the Unreal Engine commandlet. Ensure to replace \Path\To\your.uproject with your project's path. ```bash Engine\Binaries\Win64\UE4Editor-Cmd.exe \Path\To\your.uproject -NullRHI -NoSound -NoSplash -ExecCmds="Automation RunTests Angelscript.UnitTests" -TestExit "Automation Test Queue Empty+Found 0 Automation Tests, based on" -unattended -stdout -as-exit-on-error ``` -------------------------------- ### Write Unit Tests with FUnitTest Source: https://context7.com/hazelight/docs-unrealengine-angelscript/llms.txt Unit tests are functions prefixed with `Test_` and receive an `FUnitTest&` parameter. Use assertion methods like `AssertEquals`, `AssertNotNull`, and `AssertTrue` to validate behavior. The `Test_FailingExample` demonstrates how a test fails when an assertion is not met. ```angelscript // MathUtils_Test.as void Test_ClampReturnsMaxWhenValueExceedsRange(FUnitTest& T) { float Result = Math::Clamp(150.0, 0.0, 100.0); T.AssertEquals(100.0, Result); } void Test_ActorSpawnIsValid(FUnitTest& T) { FVector Loc = FVector::ZeroVector; FRotator Rot = FRotator::ZeroRotator; AMyCharacter Spawned = SpawnActor(AMyCharacter, Loc, Rot); T.AssertNotNull(Spawned); T.AssertTrue(Spawned.IsValidLowLevel()); } void Test_FailingExample(FUnitTest& T) { // Intentionally fails to demonstrate output T.AssertEquals(1, 1 + 1); // 1 != 2, test fails } ``` -------------------------------- ### Networking: Replicated Properties and RPCs in AngelScript Source: https://context7.com/hazelight/docs-unrealengine-angelscript/llms.txt Illustrates how to implement multiplayer functionality using AngelScript, including enabling actor replication, defining replicated properties with conditions (`Replicated`, `ReplicationCondition`, `ReplicatedUsing`), and setting up server, multicast, and client Remote Procedure Calls (RPCs). ```angelscript class AReplicatedCharacter : ACharacter { // Enable replication on the actor default bReplicates = true; // Replicated to all clients whenever it changes UPROPERTY(Replicated) float Health = 100.0; // Only replicated to the owning client UPROPERTY(Replicated, ReplicationCondition = OwnerOnly) int Ammo = 30; // Calls OnRep_Shield whenever replicated UPROPERTY(Replicated, ReplicatedUsing = OnRep_Shield) bool bShieldActive = false; UFUNCTION() void OnRep_Shield() { Print(f"Shield state replicated: {bShieldActive}"); } // Server RPC — reliable by default UFUNCTION(Server) void ServerFireWeapon(FVector Direction) { // Only runs on server Health -= 10.0; MulticastOnFired(Direction); } // Multicast RPC — runs on server and all clients UFUNCTION(NetMulticast, Unreliable) void MulticastOnFired(FVector Direction) { Print(f"Weapon fired in direction {Direction}"); } // Client RPC — runs only on the owning client UFUNCTION(Client) void ClientShowHitMarker() { Print("Hit marker shown to owner!"); } } ``` -------------------------------- ### Expose a Property to Unreal Engine Source: https://github.com/hazelight/docs-unrealengine-angelscript/blob/master/content/scripting/properties-and-accessors.md Add a UPROPERTY() specifier above a property to expose it to Unreal Engine. By default, properties are editable. ```csharp class AExampleActor : AActor { // Tooltip of the property UPROPERTY() float EditableProperty = 10.0; } ``` -------------------------------- ### Run Integration Tests from Command Line Source: https://context7.com/hazelight/docs-unrealengine-angelscript/llms.txt Execute Angelscript integration tests via the command line. The `-as-enable-code-coverage` flag can be added to generate coverage reports, which are saved in `Saved/CodeCoverage/index.html`. ```sh # Run integration tests from command line: Engine\Binaries\Win64\UnrealEditor-Cmd.exe "MyProject.uproject" \ -NullRHI -NoSound -NoSplash \ -ExecCmds="Automation RunTests Angelscript.IntegrationTests" \ -TestExit "Automation Test Queue Empty" \ -unattended -stdout # Enable code coverage (slows editor startup ~20s): # Project Settings > Editor > Angelscript Test Settings > Enable Code Coverage # or pass: -as-enable-code-coverage # Coverage reports are written to Saved/CodeCoverage/index.html ``` -------------------------------- ### Generate Test Commands for Potions Source: https://github.com/hazelight/docs-unrealengine-angelscript/blob/master/content/scripting/script-tests.md This function iterates through all available potions in the registry and adds their names as test commands. Use this to dynamically create a list of tests for potion-related scenarios. ```angelscript void ComplexIntegrationTest_PotionsAreTooStrongForKnight_GetTests(TArray& OutTestCommands) { for (APotion Potion : MyGame::GetPotionRegistry().GetAllPotions()) { OutTestCommands.Add(Potion.GetName().ToString()); } } ``` -------------------------------- ### Defining and Using Structs and References in AngelScript Source: https://context7.com/hazelight/docs-unrealengine-angelscript/llms.txt Shows how to declare value-type structs using the `struct` keyword and how to pass them by reference using `&` or `&out` for output parameters. Methods within structs can be plain script methods or callable from Blueprint if marked with `UFUNCTION()`. ```angelscript // Declare a struct struct FItemData { UPROPERTY() FName ItemID = n"None"; UPROPERTY() int Quantity = 1; UPROPERTY() float Weight = 0.5; // Plain script method (not callable from Blueprint) float GetTotalWeight() const { return Weight * Quantity; } } // Return a struct from a UFUNCTION UFUNCTION() FItemData CreateItem(FName ID, int Qty) { FItemData Item; Item.ItemID = ID; Item.Quantity = Qty; return Item; } // Modify a struct via reference UFUNCTION() void DoubleItemQuantity(FItemData& Item) { Item.Quantity *= 2; } // Output parameters shown as output pins in Blueprint UFUNCTION() void TryGetItem(FName ID, FItemData&out OutItem, bool&out bOutFound) { OutItem = CreateItem(ID, 1); bOutFound = ID != n"None"; } ``` -------------------------------- ### Define an Integration Test Source: https://github.com/hazelight/docs-unrealengine-angelscript/blob/master/content/scripting/script-tests.md Add this function to your .as file to define a new integration test. The function name must follow the pattern `IntegrationTest_MyTestName`. ```as void IntegrationTest_MyTestName(FIntegrationTest& T) { } ``` -------------------------------- ### Simulate Cooked Build for CI Testing Source: https://context7.com/hazelight/docs-unrealengine-angelscript/llms.txt This command simulates a cooked build to catch editor-only references in Continuous Integration (CI) pipelines. It helps ensure that no editor-specific code is accidentally included in the final build. ```sh # Simulate cooked build to catch editor-only references in CI: UnrealEditor-Cmd.exe "MyProject.uproject" -as-simulate-cooked -run=AngelscriptTest ``` -------------------------------- ### Delegate Declaration and Usage Source: https://github.com/hazelight/docs-unrealengine-angelscript/blob/master/content/scripting/delegates.md Demonstrates how to declare a delegate and use its ExecuteIfBound method within a Tick function. Functions bound to this delegate must be declared with UFUNCTION(). ```csharp public class MyActor : Actor { // Delegate declaration DECLARE_DYNAMIC_DELEGATE_OneParam(MyDelegate, float, Value); // Stored delegate instance MyDelegate StoredDelegate; public override void Tick(float DeltaSeconds) { // If the delegate is bound, execute it StoredDelegate.ExecuteIfBound(this, DeltaSeconds); } } ``` -------------------------------- ### Testing with Simulate-Cooked Mode Source: https://github.com/hazelight/docs-unrealengine-angelscript/blob/master/content/scripting/editor-script.md Use the `-as-simulate-cooked` command-line parameter with the `AngelscriptTest` commandlet to ensure your scripts compile correctly for cooked builds. This mode disables editor-only properties and compiles out `#if EDITOR` blocks. ```sh UnrealEditor-Cmd.exe "MyProject.uproject" -as-simulate-cooked -run=AngelscriptTest ``` -------------------------------- ### Using FName Literals in AngelScript Source: https://github.com/hazelight/docs-unrealengine-angelscript/blob/master/content/scripting/fname-literals.md Demonstrates how to declare and use FName literals for efficient name handling and delegate binding. The `n"NameLiteral"` syntax ensures compile-time initialization, preventing runtime name table lookups. ```angelscript delegate void FExampleDelegate(); class ANameLiteralActor : AActor { TMap ValuesByName; void UseNameLiteral() { FName NameVariable = n"MyName"; ValuesByName.Add(NameVariable, 1); FExampleDelegate Delegate; Delegate.BindUFunction(this, n"FunctionBoundToDelegate"); Delegate.ExecuteIfBound(); // Due to the name literal, no string manipulation happens // in calls to UseNameLiteral() during runtime. } UFUNCTION() void FunctionBoundToDelegate() { Print("Delegate executed"); } } ``` -------------------------------- ### Create Custom Actors and Components in Angelscript Source: https://context7.com/hazelight/docs-unrealengine-angelscript/llms.txt Define new Actor and Component types by placing class definitions in `.as` files within the `Script/` folder. Use `UPROPERTY(DefaultComponent)` for declarative component creation and `default` statements to set component properties. ```angelscript // MyCharacter.as class AMyCharacter : ACharacter { // Explicit root component UPROPERTY(DefaultComponent, RootComponent) USceneComponent SceneRoot; // Attached to SceneRoot by default UPROPERTY(DefaultComponent) USkeletalMeshComponent CharacterMesh; // Attached to CharacterMesh's RightHand socket UPROPERTY(DefaultComponent, Attach = CharacterMesh, AttachSocket = RightHand) UStaticMeshComponent WeaponMesh; // Set default values on components using 'default' statements default CharacterMesh.RelativeLocation = FVector(0.0, 0.0, 90.0); default WeaponMesh.bHiddenInGame = false; // Override component type from parent with OverrideComponent // UPROPERTY(OverrideComponent = SceneRoot) // UStaticMeshComponent RootMesh; } class UMyComponent : UActorComponent { UPROPERTY() int HitCount = 0; } ``` -------------------------------- ### Configure Integration Test Map Directory Source: https://github.com/hazelight/docs-unrealengine-angelscript/blob/master/content/scripting/script-tests.md Configure the root directory for integration test maps in your project's .ini files. This setting specifies where the engine should look for `.umap` files. ```ini [/Script/AngelscriptCode.AngelscriptTestSettings] IntegrationTestMapRoot=/Game/Testing/ ``` -------------------------------- ### Define Actor with Components and Default Properties Source: https://github.com/hazelight/docs-unrealengine-angelscript/blob/master/content/scripting/actors-components.md This snippet demonstrates defining an actor with various components (Scene, Skeletal Mesh, Static Mesh) and setting their default properties like relative location, visibility, and collision settings using the `default` statement. ```angelscript class AExampleActor : AActor { UPROPERTY(DefaultComponent, RootComponent) USceneComponent SceneRoot; UPROPERTY(DefaultComponent) USkeletalMeshComponent CharacterMesh; // The character mesh is always placed a bit above the actor root default CharacterMesh.RelativeLocation = FVector(0.0, 0.0, 50.0); UPROPERTY(DefaultComponent) UStaticMeshComponent ShieldMesh; // The shield mesh is hidden by default, and should only appear when taking damage default ShieldMesh.bHiddenInGame = true; // The shield mesh should not have any collision default ShieldMesh.SetCollisionEnabled(ECollisionEnabled::NoCollision); } ``` -------------------------------- ### Isolate Editor-Only Logic with Preprocessor Directives Source: https://context7.com/hazelight/docs-unrealengine-angelscript/llms.txt Use `#if EDITOR` preprocessor blocks or `Editor/` folders to ensure specific logic is excluded from cooked builds. This is crucial for features that should only be active in the editor environment. ```angelscript class ADebugVisualizerActor : AActor { UPROPERTY() FString DebugLabel = "MyActor"; #if EDITOR // PivotOffset is an editor-only property default PivotOffset = FVector(0, 0, 50); #endif UFUNCTION(BlueprintOverride) void ConstructionScript() { #if EDITOR SetActorLabel(DebugLabel); #endif } UFUNCTION(BlueprintOverride) void BeginPlay() { #if RELEASE // Only runs in Shipping/Test build configurations Print("Running in release build."); #endif #if TEST // Runs in Debug, Development, or Test configurations Print("Test build active."); #endif } } ``` -------------------------------- ### Networking: Replicated Properties and RPCs Source: https://context7.com/hazelight/docs-unrealengine-angelscript/llms.txt Implement multiplayer gameplay using `Replicated`, `ReplicationCondition`, `ReplicatedUsing`, and RPC specifiers for server, multicast, and client communication. ```APIDOC ## Networking: Replicated Properties and RPCs Use `Replicated`, `ReplicationCondition`, `ReplicatedUsing`, and RPC specifiers for multiplayer gameplay. ```angelscript class AReplicatedCharacter : ACharacter { // Enable replication on the actor default bReplicates = true; // Replicated to all clients whenever it changes UPROPERTY(Replicated) float Health = 100.0; // Only replicated to the owning client UPROPERTY(Replicated, ReplicationCondition = OwnerOnly) int Ammo = 30; // Calls OnRep_Shield whenever replicated UPROPERTY(Replicated, ReplicatedUsing = OnRep_Shield) bool bShieldActive = false; UFUNCTION() void OnRep_Shield() { Print(f"Shield state replicated: {bShieldActive}"); } // Server RPC — reliable by default UFUNCTION(Server) void ServerFireWeapon(FVector Direction) { // Only runs on server Health -= 10.0; MulticastOnFired(Direction); } // Multicast RPC — runs on server and all clients UFUNCTION(NetMulticast, Unreliable) void MulticastOnFired(FVector Direction) { Print(f"Weapon fired in direction {Direction}"); } // Client RPC — runs only on the owning client UFUNCTION(Client) void ClientShowHitMarker() { Print("Hit marker shown to owner!"); } } ``` ``` -------------------------------- ### Describe Current Game State Source: https://github.com/hazelight/docs-unrealengine-angelscript/blob/master/content/scripting/script-tests.md Returns a string describing the current game state, including the player's cash. It safely checks for the world and game mode existence before attempting to retrieve cash. ```AngelScript FString Describe() const { float ActualCash = -1.0; if (GetWorld() != nullptr) { auto GM = ExampleGameMode::Get(); if (GM != nullptr) { ActualCash = GM.GetCash(); } } return f" ``` -------------------------------- ### Accessing a Gameplay Tag Source: https://github.com/hazelight/docs-unrealengine-angelscript/blob/master/content/scripting/gameplaytags.md Demonstrates how to access a Gameplay Tag that has been bound to the global namespace. Non-alphanumeric characters in the tag name, including dots, are converted to underscores. ```cpp // Assuming there is a GameplayTag named "UI.Action.Escape" FGameplayTag TheTag = GameplayTags::UI_Action_Escape; ``` -------------------------------- ### Create and Return Struct from UFUNCTION Source: https://github.com/hazelight/docs-unrealengine-angelscript/blob/master/content/scripting/structs-refs.md Defines a UFUNCTION that creates an FExampleStruct and returns it. This function takes a float as input to populate the struct's members. ```cpp UFUNCTION() FExampleStruct CreateExampleStruct(float Number) { FExampleStruct ResultStruct; ResultStruct.ExampleNumber = Number; ResultStruct.ExampleString = f"{Number}"; return ResultStruct; } ``` -------------------------------- ### Execute Knight Potion Purchase Test Source: https://github.com/hazelight/docs-unrealengine-angelscript/blob/master/content/scripting/script-tests.md This integration test simulates a knight attempting to buy a potion from a potion seller. It retrieves a potion name from test parameters, looks up the potion, and finds the knight and potion seller actors. The test then instructs the knight to approach the seller. ```angelscript void ComplexIntegrationTest_PotionsAreTooStrongForKnight(FIntegrationTest& T) { FString PotionName = T.GetParam(); APotion Potion = MyGame::GetPotionRegistry().LookupPotion(PotionName); AKnight Knight = Cast(GetActorByLabel(AKnight::StaticClass(), n"Knight")); AActor PotionSeller = GetActorByLabel(AActor::StaticClass(), n"PotionSeller"); // Order the knight to walk over to the potion seller and try to buy a ``` -------------------------------- ### Override Component with UPROPERTY Source: https://github.com/hazelight/docs-unrealengine-angelscript/blob/master/content/scripting/actors-components.md Demonstrates how to override a base actor's root component with a different component type using the `OverrideComponent` specifier. This is useful for changing the type of a component defined in a parent class. ```cpp class ABaseActor : AActor { // This base actor specifies a root component that is just a scene component UPROPERTY(DefaultComponent, RootComponent) USceneComponent SceneRoot; } class AChildActor : ABaseActor { /** * Because static meshes are a type of scene component, * we can use an override component to turn the base class' root * scene component into a static mesh. */ UPROPERTY(OverrideComponent = SceneRoot) UStaticMeshComponent RootStaticMesh; } ``` -------------------------------- ### Configure Custom Game Mode for Unit Tests Source: https://github.com/hazelight/docs-unrealengine-angelscript/blob/master/content/scripting/script-tests.md Adds a custom game mode alias for unit tests by modifying project .ini files. This allows specifying a custom blueprint for test environments. ```ini [/Script/EngineSettings.GameMapsSettings] ... +GameModeClassAliases=(Name="UnitTest",GameMode="/Game/Testing/UnitTest/BP_UnitTestGameMode.BP_UnitTestGameMode_C") ``` -------------------------------- ### Structs and References Source: https://context7.com/hazelight/docs-unrealengine-angelscript/llms.txt Define value-type structs with `struct` and pass them by reference using `&` or `&out` for output parameters. ```APIDOC ## Structs and References Define value-type structs with `struct`; pass by reference using `&` or use `&out` for output parameters. ```angelscript // Declare a struct struct FItemData { UPROPERTY() FName ItemID = n"None"; UPROPERTY() int Quantity = 1; UPROPERTY() float Weight = 0.5; // Plain script method (not callable from Blueprint) float GetTotalWeight() const { return Weight * Quantity; } } // Return a struct from a UFUNCTION UFUNCTION() FItemData CreateItem(FName ID, int Qty) { FItemData Item; Item.ItemID = ID; Item.Quantity = Qty; return Item; } // Modify a struct via reference UFUNCTION() void DoubleItemQuantity(FItemData& Item) { Item.Quantity *= 2; } // Output parameters shown as output pins in Blueprint UFUNCTION() void TryGetItem(FName ID, FItemData&out OutItem, bool&out bOutFound) { OutItem = CreateItem(ID, 1); bOutFound = ID != n"None"; } ``` ``` -------------------------------- ### Spawn Blueprinted Actor with TSubclassOf Source: https://github.com/hazelight/docs-unrealengine-angelscript/blob/master/content/scripting/actors-components.md Use a TSubclassOf property to reference a blueprint actor class and the global SpawnActor() function to dynamically spawn it. Configure the ActorClass property in the editor or a child blueprint. ```cpp class AExampleSpawner : AActor { /** * Which blueprint example actor class to spawn. * This needs to be configured either in the level, * or on a blueprint child class of the spawner. */ UPROPERTY() TSubclassOf ActorClass; UFUNCTION(BlueprintOverride) void BeginPlay() { FVector SpawnLocation; FRotator SpawnRotation; AExampleActor SpawnedActor = SpawnActor(ActorClass, SpawnLocation, SpawnRotation); } } ``` -------------------------------- ### Calling Super Method in AngelScript Source: https://github.com/hazelight/docs-unrealengine-angelscript/blob/master/content/scripting/functions-and-events.md This snippet demonstrates how to call the superclass's implementation of a method in AngelScript. Ensure that the Super:: prefix is used correctly to access the parent class's function. ```angelscript int Value) { Super::BlueprintEventMethod(Value); Print("AScriptChildActor::BlueprintEventMethod()") } ``` -------------------------------- ### Find Actors and Components in AngelScript Source: https://context7.com/hazelight/docs-unrealengine-angelscript/llms.txt Use typed static methods to find components on actors, or global functions to iterate through all actors in the world. Components can be retrieved by type, name, or class, and can also be created or obtained dynamically. ```angelscript void Example_FindActorsAndComponents() { // Get all actors of a type currently in the world TArray AllCharacters; GetAllActorsOfClass(AllCharacters); for (AMyCharacter Char : AllCharacters) { // Get first component of a type on the actor USkeletalMeshComponent SkelMesh = USkeletalMeshComponent::Get(Char); if (SkelMesh != nullptr) Print(f"Found mesh: {SkelMesh.Name}"); // Get component by name UStaticMeshComponent Weapon = UStaticMeshComponent::Get(Char, n"WeaponMesh"); // Get all static mesh components on the actor TArray Meshes; Char.GetComponentsByClass(Meshes); for (UStaticMeshComponent Mesh : Meshes) Print(f"Static Mesh Component: {Mesh.Name}"); } // Get-or-create a component dynamically at runtime AMyCharacter SomeChar; UMyComponent Comp = UMyComponent::GetOrCreate(SomeChar); // Create a brand new component and attach it UStaticMeshComponent NewProp = UStaticMeshComponent::Create(SomeChar); NewProp.AttachToComponent(SomeChar.CharacterMesh); } ``` -------------------------------- ### Expose Functions to Blueprint Source: https://github.com/hazelight/docs-unrealengine-angelscript/blob/master/content/scripting/functions-and-events.md Make functions callable from Blueprint by adding the `UFUNCTION()` specifier. By default, functions exposed this way are considered `BlueprintCallable`. ```angelscript class AExampleActor : AActor { UFUNCTION() void MyMethodForBlueprint() { Print("I can be called from a blueprint!"); } } ``` -------------------------------- ### Formatted String with Integer Padding and Leading Zeros Source: https://github.com/hazelight/docs-unrealengine-angelscript/blob/master/content/scripting/format-strings.md Format integers to a specific width and pad with leading zeros using format specifiers like `:010d`. ```angelscript Print(f"Extended to 10 digits with leading zeroes: {400 :010d}"); // 0000000400 ``` -------------------------------- ### Declare a Global Function for Blueprints Source: https://github.com/hazelight/docs-unrealengine-angelscript/blob/master/content/scripting/functions-and-events.md Use the UFUNCTION() macro on a global script function to make it callable from Blueprints. Comments above the function declaration will appear as tooltips in the Blueprint editor. ```angelscript // Example global function that moves an actor somewhat UFUNCTION() void ExampleGlobalFunctionMoveActor(AActor Actor, FVector MoveAmount) { Actor.ActorLocation += MoveAmount; } ```