### Test Script Compilation with Simulate-Cooked Mode Source: https://angelscript.hazelight.se/scripting/editor-script Provides a command-line example for testing project scripts in a simulated cooked environment. This ensures that editor-only dependencies are correctly handled before final deployment. ```Batch UnrealEditor-Cmd.exe "MyProject.uproject" -as-simulate-cooked -run=AngelscriptTest ``` -------------------------------- ### Retrieve and Use Unreal Subsystems Source: https://angelscript.hazelight.se/scripting/subsystems Demonstrates how to access an existing Unreal Engine subsystem using the static Get() method and invoke its functions. This example specifically shows the creation of a new level via the ULevelEditorSubsystem. ```Angelscript void TestCreateNewLevel() { auto LevelEditorSubsystem = ULevelEditorSubsystem::Get(); LevelEditorSubsystem.NewLevel("/Game/NewLevel"); } ``` -------------------------------- ### Access Local Player Subsystems Source: https://angelscript.hazelight.se/scripting/subsystems Explains how to retrieve a local player subsystem by providing a ULocalPlayer instance or an APlayerController to the Get() method. ```Angelscript class UMyPlayerSubsystem : UScriptLocalPlayerSubsystem { } void UseScriptedPlayerSubsystem() { ULocalPlayer RelevantPlayer = Gameplay::GetPlayerController(0).LocalPlayer; auto MySubsystem = UMyPlayerSubsystem::Get(RelevantPlayer); } ``` -------------------------------- ### Running Angelscript Unit Tests via Command Line Source: https://angelscript.hazelight.se/scripting/script-tests This command line example shows how to execute Angelscript unit tests using the UE4Editor executable. It includes parameters for specifying the project, disabling certain editor features, and instructing the editor to run tests and exit. ```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 ``` -------------------------------- ### Actor Construction Script Example Source: https://angelscript.hazelight.se/scripting/actors-components Illustrates how to override the ConstructionScript() event to dynamically create and configure components on an actor during its construction phase. This allows for procedural generation of actor elements based on properties set in the editor. ```angelscript 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); } } } ``` -------------------------------- ### Use Preprocessor Blocks for Editor-Only Code Source: https://angelscript.hazelight.se/scripting/editor-script Demonstrates how to use the #if EDITOR preprocessor directive to wrap code that should only exist within the editor environment. This prevents compilation errors in cooked game builds by excluding the enclosed logic. ```Angelscript class AExampleActor : AActor { #if EDITOR default PivotOffset = FVector(0, 0, 10); #endif UFUNCTION(BlueprintOverride) void ConstructionScript() { #if EDITOR SetActorLabel("Example Actor Label"); #endif } } ``` -------------------------------- ### Angelscript Unit Test Example Source: https://angelscript.hazelight.se/scripting/script-tests A basic example of an Angelscript unit test function. It demonstrates how to use assertion methods like AssertTrue, AssertEquals, and AssertNotNull to validate test conditions. These tests are typically placed in files ending with '_Test.as'. ```angelscript void Test_NameOfTheTestCase(FUnitTest& T) { // Fails the test. T.AssertTrue(false); T.AssertEquals(1, 1 + 1); T.AssertNotNull(nullptr); } ``` -------------------------------- ### Retrieve Components from an Actor in AngelScript Source: https://angelscript.hazelight.se/scripting/actors-components Explains how to find existing components on an actor using `UMyComponentClass::Get()` or `UMyComponentClass::GetOrCreate()`. `Get()` returns `nullptr` if not found, while `GetOrCreate()` creates the component if it doesn't exist. Named components can be retrieved using a second argument. ```angelscript AActor Actor; // Retrieve the first skeletal mesh component we can find on the actor USkeletalMeshComponent SkelComp = USkeletalMeshComponent::Get(Actor); // Find the specific skeletal mesh component with this component name USkeletalMeshComponent WeaponComp = USkeletalMeshComponent::Get(Actor, n"WeaponMesh"); // 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, n"ClimbingInteraction"); ``` -------------------------------- ### Get Actor Components by Class Source: https://angelscript.hazelight.se/scripting/actors-components Shows how to retrieve all components of a specific type attached to an actor using the Actor.GetComponentsByClass() method. This function populates a provided array with components matching the specified type. ```angelscript AActor Actor; TArray StaticMeshComponents; Actor.GetComponentsByClass(StaticMeshComponents); for (UStaticMeshComponent MeshComp : StaticMeshComponents) { Print(f"Static Mesh Component: {MeshComp.Name}"); } ``` -------------------------------- ### Implementing a Custom Latent Automation Command in AngelScript Source: https://angelscript.hazelight.se/scripting/script-tests Provides an example of a custom latent automation command, `UGetsShotXTimes`, derived from `ULatentAutomationCommand`. This command checks if a target actor (`ABulletSponge`) has been hit a specified number of times. The `Update` function returns true when the condition is met, signaling the command's completion. The `Describe` function provides a string representation of the command's status. ```AngelScript class UGetsShotXTimes : ULatentAutomationCommand { private ABulletSponge BulletSponge; private int ExpectedNumHits; UGetsShotXTimes(ABulletSponge Target, int X) { BulletSponge = Target; ExpectedNumHits = X; } UFUNCTION(BlueprintOverride) bool Update() { // Note: actors can get DestroyActor'd at any time, so fail nicely if that happens! ensure(IsValid(BulletSponge)); return BulletSponge.NumTimesHit > ExpectedNumHits; } UFUNCTION(BlueprintOverride) FString Describe() const { return BulletSponge.GetPathName() + ": bullet sponge got hit " + BulletSponge.NumTimesHit + "/" + ExpectedNumHits; } } ``` -------------------------------- ### Implement Countdown Logic with UPROPERTY and UFUNCTION Source: https://angelscript.hazelight.se/getting-started/introduction Demonstrates how to expose variables to the Unreal Editor using UPROPERTY and implement game logic by overriding BeginPlay and Tick events. ```Angelscript class AIntroductionActor : AActor { UPROPERTY() float CountdownDuration = 5.0; float CurrentTimer = 0.0; bool bCountdownActive = false; UFUNCTION(BlueprintOverride) void BeginPlay() { CurrentTimer = CountdownDuration; bCountdownActive = true; } UFUNCTION(BlueprintOverride) void Tick(float DeltaSeconds) { if (bCountdownActive) { CurrentTimer -= DeltaSeconds; if (CurrentTimer <= 0.0) { Print("Countdown was completed!"); bCountdownActive = false; } } } } ``` -------------------------------- ### Get All Actors of Class Source: https://angelscript.hazelight.se/scripting/actors-components Demonstrates the use of the global GetAllActorsOfClass() function to find all actors of a particular type currently present in the world. The function populates a provided array with the found actors. ```angelscript // Find all niagara actors currently in the level TArray NiagaraActors; GetAllActorsOfClass(NiagaraActors); ``` -------------------------------- ### Angelscript Integration Test Function Source: https://angelscript.hazelight.se/scripting/script-tests An example of an Angelscript integration test function. These tests are designed for longer code flows and gameplay scenarios. The function takes an FIntegrationTest object as a parameter, which can be used to interact with the game world. ```angelscript void IntegrationTest_MyTestName(FIntegrationTest& T) { } ``` -------------------------------- ### Spawn Actor from Script Source: https://angelscript.hazelight.se/scripting/actors-components Demonstrates how to spawn a new actor instance of a specified class at a given location and rotation using the global SpawnActor() function. This is the fundamental method for creating actors dynamically in script. ```angelscript // Spawn a new Example Actor at the specified location and rotation FVector SpawnLocation; FRotator SpawnRotation; AExampleActor SpawnedActor = SpawnActor(AExampleActor, SpawnLocation, SpawnRotation); ``` -------------------------------- ### Create New Components in AngelScript Source: https://angelscript.hazelight.se/scripting/actors-components Demonstrates how to create new components dynamically on an actor using `UMyComponentClass::Create()`. An optional component name can be provided; otherwise, one is auto-generated. Components can also be attached to other components using `AttachToComponent`. ```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); ``` -------------------------------- ### Define and Implement a Custom World Subsystem Source: https://angelscript.hazelight.se/scripting/subsystems Shows how to create a custom subsystem by inheriting from UScriptWorldSubsystem. It includes overriding Initialize and Tick functions and adding custom UFUNCTIONs accessible by other scripts or blueprints. ```Angelscript class UMyGameWorldSubsystem : UScriptWorldSubsystem { UFUNCTION(BlueprintOverride) void Initialize() { Print("MyGame World Subsystem Initialized!"); } UFUNCTION(BlueprintOverride) void Tick(float DeltaTime) { Print("Tick"); } UFUNCTION() void LookAtMyActor(AActor Actor) { } } void UseMyGameWorldSubsystem() { auto MySubsystem = UMyGameWorldSubsystem::Get(); MySubsystem.LookAtMyActor(nullptr); } ``` -------------------------------- ### Implement Save Game Upgrade Integration Test in Angelscript Source: https://angelscript.hazelight.se/scripting/script-tests Defines a latent automation command to verify backwards compatibility of save files. It includes the test entry point, map override configuration, and the command class with lifecycle hooks for setup, validation, and reporting. ```Angelscript void IntegrationTest_UpgradeSaveGameV1(FIntegrationTest& T) { T.AddLatentAutomationCommand(UTestUpgradeSaveGameV1()); } FString IntegrationTest_UpgradeSaveGameV1_GetMapName() { return "/Game/IS/Maps/ISMainMap"; } class UTestUpgradeSaveGameV1 : ULatentAutomationCommand { float CashFromV1Save = 12345.0; FString V1SaveFileName = "IntegrationTest_UpgradeSaveGameV1"; UFUNCTION(BlueprintOverride) void Before() { auto GM = ExampleGameMode::Get(); auto ExampleSaveSystem = UExampleSaveSystem::Get(); ExampleSaveSystem.SelectSaveFile(V1SaveFileName); ExampleSaveSystem.LoadWithoutReload(V1SaveFileName); } UFUNCTION(BlueprintOverride) bool Update() { auto GM = ExampleGameMode::Get(); if (GM != nullptr && Math::IsNearlyEqual(CashFromV1Save, GM.GetCash())) { return true; } return false; } UFUNCTION(BlueprintOverride) FString Describe() const { float ActualCash = -1.0; if (GetWorld() != nullptr) { auto GM = ExampleGameMode::Get(); if (GM != nullptr) { ActualCash = GM.GetCash(); } } return f"Expected cash: {CashFromV1Save}, Actual cash: {ActualCash} (-1 is null)"; } } ``` -------------------------------- ### Pass and Return Structs from AngelScript Functions Source: https://angelscript.hazelight.se/scripting/structs-refs Shows how to create, pass, and return structs from AngelScript functions and UFUNCTIONs. This includes initializing a struct and assigning values to its properties. ```angelscript UFUNCTION() FExampleStruct CreateExampleStruct(float Number) { FExampleStruct ResultStruct; ResultStruct.ExampleNumber = Number; ResultStruct.ExampleString = f"{Number}"; return ResultStruct; } UFUNCTION(BlueprintPure) bool IsNumberInStructEqual(FExampleStruct Struct, float TestNumber) { return Struct.ExampleNumber == TestNumber; } ``` -------------------------------- ### Applying Format Specifiers in AngelScript Source: https://angelscript.hazelight.se/scripting/format-strings Shows how to use format specifiers to control precision, padding, base conversion (hex/binary), and alignment within f-strings. ```AngelScript Print(f"Three Decimals: {ActorLocation.Z :.3}"); Print(f"Extended to 10 digits with leading zeroes: {400 :010d}"); Print(f"Hexadecimal: {20 :#x}"); Print(f"Binary: {1574 :b}"); Print(f"Binary 32 Bits: {1574 :#032b}"); Print(f"Aligned: {GetName() :>40}"); Print(f"Aligned: {GetName() :_<40}"); Print(f"{DeltaSeconds =:.0}"); Print(f"{ESlateVisibility::Collapsed :n}"); ``` -------------------------------- ### Executing a Complex Integration Test with Latent Commands in AngelScript Source: https://angelscript.hazelight.se/scripting/script-tests Details a complex integration test scenario where a knight attempts to buy a potion. The `ComplexIntegrationTest_PotionsAreTooStrongForKnight` function retrieves necessary actors and then adds a latent automation command, `UExpectResponse`, to verify the interaction's outcome. This test setup allows for verifying specific conversational or action-based responses within the game. ```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 potion. Knight.BuyPotionFrom(PotionSeller, Potion); T.AddLatentAutomationCommand(UExpectResponse("My potions are too strong for you traveller.", Knight, PotionSeller)); } ``` -------------------------------- ### Implement Actor Replication and RPCs in AngelScript Source: https://angelscript.hazelight.se/scripting/networking-features Demonstrates how to define a replicated actor class in AngelScript. It includes setting the default replication property, using various replication conditions, and defining a notification function for replicated properties. ```AngelScript class AReplicatedActor : AActor { // Set the actor's replicates property to default to true default bReplicates = true; // Will always be replicated when it changes UPROPERTY(Replicated) bool bReplicatedBool = true; // Only replicates to the owner UPROPERTY(Replicated, ReplicationCondition = OwnerOnly) int ReplicatedInt = 0; // Calls OnRep_ReplicatedValue whenever it is replicated UPROPERTY(Replicated, ReplicatedUsing = OnRep_ReplicatedValue) int ReplicatedValue = 0; UFUNCTION() void OnRep_ReplicatedValue() { Print("Replicated Value has changed!"); } } ``` -------------------------------- ### Attach Components to Scripted Actor Source: https://angelscript.hazelight.se/getting-started/introduction Shows how to define and attach Scene, Static Mesh, and Billboard components to an Actor using the DefaultComponent and Attach specifiers. ```Angelscript class AIntroductionActor : AActor { UPROPERTY(DefaultComponent, RootComponent) USceneComponent SceneRoot; UPROPERTY(DefaultComponent, Attach = SceneRoot) UStaticMeshComponent Mesh; UPROPERTY(DefaultComponent, Attach = SceneRoot) UBillboardComponent Billboard; } ``` -------------------------------- ### Implementing Delegates in AngelScript Source: https://angelscript.hazelight.se/scripting/delegates Demonstrates how to declare a delegate type, bind it to a UFunction, and execute it conditionally. Delegates are used for single-target callbacks and require UFunction-marked methods. ```AngelScript delegate void FExampleDelegate(UObject Object, float Value); class ADelegateExample : AActor { FExampleDelegate StoredDelegate; UFUNCTION(BlueprintOverride) void BeginPlay() { StoredDelegate.BindUFunction(this, n"OnDelegateExecuted"); StoredDelegate = FExampleDelegateSignature(this, n"OnDelegateExecuted"); } UFUNCTION() private void OnDelegateExecuted(UObject Object, float Value) { Print(f"Delegate was executed with object {Object} and value {Value}"); } UFUNCTION(BlueprintOverride) void Tick(float DeltaSeconds) { StoredDelegate.ExecuteIfBound(this, DeltaSeconds); } } ``` -------------------------------- ### Implementing Events in AngelScript Source: https://angelscript.hazelight.se/scripting/delegates Shows how to declare an event, add multiple UFunction handlers, and broadcast to all subscribers. Events support multicast functionality, allowing multiple functions to respond to a single trigger. ```AngelScript event void FExampleEvent(int Counter); class AEventExample : AActor { UPROPERTY() FExampleEvent OnExampleEvent; private int CallCounter = 0; UFUNCTION(BlueprintOverride) void BeginPlay() { OnExampleEvent.AddUFunction(this, n"FirstHandler"); OnExampleEvent.AddUFunction(this, n"SecondHandler"); } UFUNCTION() private void FirstHandler(int Counter) { Print("Called first handler"); } UFUNCTION() private void SecondHandler(int Counter) { Print("Called second handler"); } UFUNCTION(BlueprintOverride) void Tick(float DeltaSeconds) { CallCounter += 1; OnExampleEvent.Broadcast(CallCounter); } } ``` -------------------------------- ### Setting Default Property Values in AngelScript Source: https://angelscript.hazelight.se/scripting/cpp-differences Illustrates how to set default values for properties and subobjects directly within the class body using the `default` keyword in AngelScript. This approach replaces traditional C++ constructors for default value initialization. ```angelscript class AExampleActor : AActor { // Set default values for class properties in the class body UPROPERTY() float ConfigurableValue = 5.0; // Set default values for subobjects with `default` statements UPROPERTY(DefaultComponent) UCapsuleComponent CapsuleComponent; default CapsuleComponent.CapsuleHalfHeight = 88.0; default CapsuleComponent.CapsuleRadius = 40.0; default CapsuleComponent.bGenerateOverlapEvents = true; } ``` -------------------------------- ### Object References and Transformations in AngelScript Source: https://angelscript.hazelight.se/scripting/cpp-differences Demonstrates how to teleport an actor to another actor's location using object references in AngelScript. This replaces C++ pointer syntax with dot notation for accessing properties and methods. ```angelscript void TeleportActorToOtherActor(AActor ActorReference, AActor TeleportToActor) { FTransform TeleportToTransform = TeleportToActor.GetActorTransform(); ActorReference.SetActorTransform(TeleportToTransform); } ``` -------------------------------- ### Create Basic Actor Class in Angelscript Source: https://angelscript.hazelight.se/getting-started/introduction Defines a basic Actor class inheriting from AActor. This serves as the foundation for all scripted actors in the project. ```Angelscript class AIntroductionActor : AActor { } ``` -------------------------------- ### Set a Timer using System Library Source: https://angelscript.hazelight.se/scripting/function-libraries Demonstrates how to use the System::SetTimer function within an AActor class to trigger a callback after a specified delay. This requires the target object and the name of the function to execute as a name literal. ```Angelscript class ATimerExample : AActor { UFUNCTION(BlueprintOverride) void BeginPlay() { // Execute this.OnTimerExecuted() after 2 seconds System::SetTimer(this, n"OnTimerExecuted", 2.0, bLooping = false); } UFUNCTION() private void OnTimerExecuted() { Print("Timer executed!"); } } ``` -------------------------------- ### Interpolating Variables and Expressions in AngelScript Source: https://angelscript.hazelight.se/scripting/format-strings Demonstrates basic usage of f-strings to inject variable values and function results into strings. It also shows the '=' syntax for debugging expressions and their values. ```AngelScript Print(f"Called from actor {GetName()} at location {ActorLocation}"); Print(f"{DeltaSeconds =}"); ``` -------------------------------- ### Using FName Literals in AngelScript Source: https://angelscript.hazelight.se/scripting/fname-literals Demonstrates how to declare FName variables using literals and bind them to UFunctions. This approach ensures that name table lookups occur at compile time rather than runtime. ```AngelScript class ANameLiteralActor : AActor { TMap ValuesByName; void UseNameLiteral() { FName NameVariable = n"MyName"; ValuesByName.Add(NameVariable, 1); FExampleDelegate Delegate; Delegate.BindUFunction(this, n"FunctionBoundToDelegate"); Delegate.ExecuteIfBound(); } UFUNCTION() void FunctionBoundToDelegate() { Print("Delegate executed"); } } ``` -------------------------------- ### Extend USTRUCTs with ScriptMixin Source: https://angelscript.hazelight.se/cpp-bindings/mixin-libraries Demonstrates how to add methods to a USTRUCT like FVector by creating a UCLASS with the ScriptMixin metadata. Static functions with the first argument matching the target type are automatically bound as methods. ```C++ UCLASS(Meta = (ScriptMixin = "FVector")) class UFVectorScriptMixinLibrary : public UObject { GENERATED_BODY() public: // This will be accessible in script as // FVector Vector; // Vector.ResetTo(4.0); UFUNCTION(ScriptCallable) static void ResetTo(FVector& Vector, float NewValue) { Vector = FVector(NewValue, NewValue, NewValue); } // This will become a const method, as it takes // a const reference to the mixin type: // Usable in script as both Vector.SummedValue // or Vector.GetSummedValue() UFUNCTION(ScriptCallable) static float GetSummedValue(const FVector& Vector) { return Vector.X+Vector.Y+Vector.Z; } } ``` -------------------------------- ### Generating Dynamic Test Cases in AngelScript Source: https://angelscript.hazelight.se/scripting/script-tests Illustrates how to dynamically generate test cases for complex integration tests. The `ComplexIntegrationTest_PotionsAreTooStrongForKnight_GetTests` function iterates through a registry of potions and adds a unique test command string for each potion to an output array. This allows for parameterized testing based on available game data. ```AngelScript void ComplexIntegrationTest_PotionsAreTooStrongForKnight_GetTests(TArray& OutTestCommands) { for (APotion Potion: MyGame::GetPotionRegistry().GetAllPotions()) { OutTestCommands.Add(Potion.GetName().ToString()); } } ``` -------------------------------- ### Spawn Blueprint Actor using TSubclassOf Source: https://angelscript.hazelight.se/scripting/actors-components Explains how to spawn a blueprint-derived actor by using a TSubclassOf property to reference the blueprint class. The global SpawnActor() function is then used with this class reference to instantiate the blueprint. ```angelscript 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); } } ``` -------------------------------- ### Implement Separate Base and Blueprint Events in AngelScript Source: https://angelscript.hazelight.se/scripting/functions-and-events Illustrates a pattern for creating separate base script events and Blueprint events. This ensures script code always runs and allows Blueprints to add functionality without breaking the base implementation. ```angelscript class AExamplePickupActor : AActor { void PickedUp() { // We always want this script code to run, even if our blueprint child wants to do something too Print(f"Pickup {this} was picked up!"); SetActorHiddenInGame(false); // Call the separate blueprint event BP_PickedUp(); } // Allows blueprints to add functionality, does not contain any code UFUNCTION(BlueprintEvent, DisplayName = "Picked Up") void BP_PickedUp() {} } ``` -------------------------------- ### Extend UCLASSes with ScriptMixin Source: https://angelscript.hazelight.se/cpp-bindings/mixin-libraries Shows how to add methods to UCLASS types by using a pointer to the target class as the first argument in the static mixin function. ```C++ UCLASS(Meta = (ScriptMixin = "AActor")) class UMyActorMixinLibrary : public UObject { GENERATED_BODY() public: // This can be used in script as: // Actor.TeleportToOrigin(); UFUNCTION(ScriptCallable) static void TeleportToOrigin(AActor* Actor) { Actor->SetActorLocation(FVector(0, 0, 0)); } } ``` -------------------------------- ### Accessing Gameplay Tags in AngelScript Source: https://angelscript.hazelight.se/scripting/gameplaytags Demonstrates how to access a specific Gameplay Tag by converting its dot-notation path into an underscore-separated global constant. The system automatically binds these tags to the GameplayTags namespace for easy reference. ```AngelScript // Assuming there is a GameplayTag named "UI.Action.Escape" FGameplayTag TheTag = GameplayTags::UI_Action_Escape; ``` -------------------------------- ### Configuring Custom Game Mode for Angelscript Unit Tests Source: https://angelscript.hazelight.se/scripting/script-tests This INI file snippet demonstrates how to configure a custom game mode for Angelscript unit tests. By adding this setting, you can specify a blueprint to be used for all unit tests, allowing for consistent test environments. ```ini [/Script/EngineSettings.GameMapsSettings] ... +GameModeClassAliases=(Name="UnitTest",GameMode="/Game/Testing/UnitTest/BP_UnitTestGameMode.BP_UnitTestGameMode_C") ``` -------------------------------- ### Configure Component Attachments in AngelScript Source: https://angelscript.hazelight.se/scripting/actors-components Explains how to define the attachment hierarchy for components using `Attach` and `AttachSocket` specifiers in `UPROPERTY`. If not specified, components attach to the actor's root by default. The `RootComponent` specifier explicitly sets the root component. ```angelscript class AExampleActor : AActor { // Explicit root component UPROPERTY(DefaultComponent, RootComponent) USceneComponent SceneRoot; // Will be attached to SceneRoot by default, as no attachment is specified UPROPERTY(DefaultComponent) USkeletalMeshComponent CharacterMesh; // Will be attached to the CharacterMesh' RightHand socket UPROPERTY(DefaultComponent, Attach = CharacterMesh, AttachSocket = RightHand) UStaticMeshComponent WeaponMesh; // Will be attached to the WeaponMesh UPROPERTY(DefaultComponent, Attach = WeaponMesh) UStaticMeshComponent ScopeMesh; } ``` -------------------------------- ### Expose Global AngelScript Functions to Blueprint Source: https://angelscript.hazelight.se/scripting/functions-and-events Shows how to make global scope AngelScript functions callable from Blueprints by adding the `UFUNCTION()` specifier. These function like static functions in Blueprint Function Libraries. ```angelscript // Example global function that moves an actor somewhat UFUNCTION() void ExampleGlobalFunctionMoveActor(AActor Actor, FVector MoveAmount) { Actor.ActorLocation += MoveAmount; } ``` -------------------------------- ### Declare Plain Script Functions in AngelScript Source: https://angelscript.hazelight.se/scripting/functions-and-events Demonstrates how to declare plain script functions as methods within a class or as global functions. These functions are only accessible from script and not from Blueprints. ```angelscript class AExampleActor : AActor { void MyMethod() { MyGlobalFunction(this); } } void MyGlobalFunction(AActor Actor) { if (!Actor.IsHidden()) { Actor.DestroyActor(); } } ``` -------------------------------- ### Configuring Integration Test Map Directory Source: https://angelscript.hazelight.se/scripting/script-tests This INI file setting allows you to specify the root directory for integration test maps. By default, integration tests look for a .umap file with the same name as the test in a 'Testing' folder. This setting provides flexibility in organizing test maps. ```ini [/Script/AngelscriptCode.AngelscriptTestSettings] IntegrationTestMapRoot=/Game/Testing/ ``` -------------------------------- ### Add Default Components to Actors in AngelScript Source: https://angelscript.hazelight.se/scripting/actors-components Shows how to specify default components for an actor using the `DefaultComponent` specifier within the actor's class definition. These components are automatically created when the actor is spawned. ```angelscript class AExampleActor : AActor { UPROPERTY(DefaultComponent) USceneComponent SceneRoot; UPROPERTY(DefaultComponent) UMyComponent MyComponent; } ``` -------------------------------- ### Enqueueing Custom Latent Automation Commands in AngelScript Source: https://angelscript.hazelight.se/scripting/script-tests Demonstrates how to enqueue a custom latent automation command within an integration test. The `AddLatentAutomationCommand` function takes a `ULatentAutomationCommand` object, which defines the behavior and conditions for the command to complete. This allows for custom test logic beyond the default framework commands. ```AngelScript void IntegrationTest_AlienShootsRepeatedly(FIntegrationTest& T) { AActor A = GetActorByLabel(ABulletSponge::StaticClass(), n"BulletSponge"); ABulletSponge Floor = Cast(A); T.AddLatentAutomationCommand(UGetsShotXTimes(Floor, 2)); } ``` -------------------------------- ### Generic Component Operations on Actors in AngelScript Source: https://angelscript.hazelight.se/scripting/actors-components Provides alternative methods for component management directly on actor objects when a dynamic `TSubclassOf<>` or `UClass` is available. These include `Actor.GetComponent()`, `Actor.GetOrCreateComponent()`, and `Actor.CreateComponent()`. ```angelscript // Example usage with a dynamic UClass (assuming 'MyComponentClass' is a UClass variable) // Actor.GetComponent(MyComponentClass); // Actor.GetOrCreateComponent(MyComponentClass, n"OptionalComponentName"); // Actor.CreateComponent(MyComponentClass); ``` -------------------------------- ### Implement Property Accessor Functions Source: https://angelscript.hazelight.se/scripting/properties-and-accessors Uses the property keyword on Get/Set methods to allow functions to be accessed like standard class properties. This enables cleaner syntax when retrieving or calculating values. ```AngelScript class AExampleActor : AActor { FVector GetRotatedOffset() const property { return ActorRotation.RotateVector(FVector(0.0, 1.0, 1.0)); } UFUNCTION(BlueprintOverride) void BeginPlay() { Print("Offset at BeginPlay: "+RotatedOffset); } } ``` -------------------------------- ### Define Struct with Properties in AngelScript Source: https://angelscript.hazelight.se/scripting/structs-refs Demonstrates how to declare a struct in AngelScript, including properties that can be exposed to Blueprint using UPROPERTY() and those that remain hidden. Structs behave as value types and cannot contain UFUNCTIONs. ```angelscript struct FExampleStruct { UPROPERTY() float ExampleNumber = 4.0; UPROPERTY() FString ExampleString = "Example String"; float ExampleHiddenNumber = 3.0; }; ``` -------------------------------- ### Override Script Method with Super Call (AngelScript) Source: https://angelscript.hazelight.se/scripting/functions-and-events Demonstrates overriding a plain script method in a child class and calling the parent's implementation using 'Super::'. This is applicable to any script method, as they are all virtual by default. ```AngelScript class AScriptParentActor : AActor { void PlainMethod(FVector Location) { Print("AScriptParentActor::PlainMethod()") } UFUNCTION(BlueprintEvent) void BlueprintEventMethod(int Value) { Print("AScriptParentActor::BlueprintEventMethod()") } } class AScriptChildActor : AScriptParentActor { // Any script method can be overridden void PlainMethod(FVector Location) override { Super::PlainMethod(Location) Print("AScriptChildActor::PlainMethod()") } // Overriding a parent BlueprintEvent requires BlueprintOverride UFUNCTION(BlueprintOverride) void BlueprintEventMethod(int Value) { Super::BlueprintEventMethod(Value) Print("AScriptChildActor::BlueprintEventMethod()") } } ``` -------------------------------- ### Defining an Actor for Latent Command Testing in AngelScript Source: https://angelscript.hazelight.se/scripting/script-tests Defines an `ABulletSponge` actor class used in latent automation tests. It includes a `NumTimesHit` variable and overrides the `BeginPlay` and `TakeAnyDamage` functions. `BeginPlay` sets up a delegate to call `TakeAnyDamage` when the actor receives any damage, incrementing `NumTimesHit` each time. ```AngelScript class ABulletSponge : AStaticMeshActor { int NumTimesHit = 0; UFUNCTION(BlueprintOverride) void BeginPlay() { OnTakeAnyDamage.AddUFunction(this, n"TakeAnyDamage"); } UFUNCTION() private void TakeAnyDamage(AActor DamagedActor, float32 Damage, const UDamageType DamageType, AController InstigatedBy, AActor DamageCauser) { NumTimesHit++; } } ``` -------------------------------- ### Set Default Property Values in AngelScript Source: https://angelscript.hazelight.se/scripting/actors-components Illustrates how to assign default values to actor component properties using `default` statements. This allows pre-configuration of components like location, visibility, or collision settings. ```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); } ``` -------------------------------- ### Expose Properties to Unreal Editor Source: https://angelscript.hazelight.se/scripting/properties-and-accessors Uses the UPROPERTY() specifier to expose script variables to the Unreal Engine editor. Includes various specifiers like EditDefaultsOnly, EditInstanceOnly, and VisibleAnywhere to control editing permissions. ```AngelScript class AExampleActor : AActor { UPROPERTY() float EditableProperty = 10.0; UPROPERTY(EditDefaultsOnly) float DefaultsProperty = 10.0; UPROPERTY(EditInstanceOnly) FVector InstanceProperty = FVector(0.0, 100.0, 0.0); UPROPERTY(VisibleAnywhere) FName VisibleProperty = NAME_None; UPROPERTY(NotEditable) TArray VisibleProperty; } ``` -------------------------------- ### Define Actor and Component Classes in AngelScript Source: https://angelscript.hazelight.se/scripting/actors-components Demonstrates how to create new actor and component types by defining classes that inherit from base Unreal Engine types like AActor and UActorComponent. No explicit UCLASS specifier is needed as the plugin handles it automatically. ```angelscript class AMyActor : AActor { } class UMyComponent : UActorComponent { } ```