# Introduction

This guide aims to be a new community resource for Unreal Engine 4. The first initiative behind this guide is to find and preserve as much of the original Unreal Engine 4 Wiki as possible. In addition to preserving the original wiki content, we're also planning on publishing new and updated content that may be useful to the Unreal development community. This can be seen with the new "Quick Reference" section.

If you're looking to help us in the archiving effort, [click here](/4.25/wiki-archives#a-new-community-driven-wiki-was-launched-for-unreal-engine-4).

## I want to contribute, how can I help?

1. [Fork the repository for this site on Github](https://github.com/NickGlenn/Unreal-Engine-4-Community-Guide).
2. Create a Pull Request in Github for the changes made to the book.
3. Assign [@nickglenn](https://github.com/nickglenn) as a reviewer.


# Quick Reference


# C++ Data Type Snippets

This page contains several code snippets for quickly creating C++ data types that can be used with Blueprints. Use this as reference or as a copy + paste resource as needed.

## Interfaces

For more information about interfaces in Unreal, [check out this wiki article](/4.25/wiki-archives/macros-and-data-types/interfaces-in-c++).

* You need to define two classes: `U<Name>` and `I<Name>`. The second class is what your C++ code will extend to implement the interface.

```cpp
UINTERFACE(BlueprintType)
class MYPROJECT_API UExample : public UInterface
{
  GENERATED_BODY()
};

class MYPROJECT_API IExample
{
  GENERATED_BODY()

public:

  UFUNCTION(BlueprintNativeEvent, BlueprintCallable)
  bool NativeEventExampleMethod();

  UFUNCTION(BlueprintImplementableEvent, BlueprintCallable)
  bool BlueprintEventExampleMethod();

};
```

## Structs

For more information about structs in Unreal, [check out this wiki article](/4.25/wiki-archives/macros-and-data-types/structs-ustructs-theyre-awesome).

* To access your struct from Blueprint, make sure to add the `BlueprintType` keyword to the `USTRUCT` macro.
* Structs must have a default constructor.
* It's Unreal coding standard to prefix your structs with a capital `F`.
* You cannot use the `UFUNCTION` macro with methods on structs.

```cpp
USTRUCT(BlueprintType)
struct MYPROJECT_API FExample
{
    GENERATED_BODY()
    
public:

    UPROPERTY(BlueprintReadOnly)
    int32 SomeValue;

};
```


# The UPROPERTY Macro

A quick reference around Unreal's UPROPERTY macro in C++ and available attributes.

> This article is a work in progress, come back later.


# The UFUNCTION Macro

A quick reference around Unreal's UFUNCTION macro in C++ and available keywords.

## Keywords

These keywords are also valid for the `UDELEGATE` macro.

### **BlueprintAuthorityOnly**

This function will only execute from Blueprint code if running on a machine with network authority (a server, dedicated server, or single-player game).

* Useful for visually marking methods in Blueprint for designers.
* Will still execute on non-network authority clients when called from C++.

```cpp
UFUNCTION(BlueprintCallable, BlueprintAuthorityOnly)
void SpawnProjectile();
```

### **BlueprintCallable**

&#x20;This function can be executed in a Blueprint and will appear in Blueprint tooling.

* Using the `const` C++ keyword on the related method will remove the execution pin, making this a pure Blueprint function node.

```cpp
UFUNCTION(BlueprintCallable)
void SetValue(float InValue);
```

### **BlueprintCosmetic**

This function is cosmetic and will not run on dedicated servers.

* Will still execute on network authority servers when called from C++.

```cpp
UFUNCTION(BlueprintImplementableEvent, BlueprintCosmetic)
void PlayHitEffects();
```

### BlueprintGetter

&#x20;This function will be used as the accessor for a Blueprint-exposed property. This specifier implies `BlueprintPure` and `BlueprintCallable`.

> More information needed about this keyword.

### BlueprintInternalUseOnly

Indicates that the function should not be exposed to the end user.

> More information needed about this keyword.

### BlueprintImplementableEvent

This function is designed to be overridden (implemented) in Blueprint.

* Do not provide a body for this function; the auto-generated code will include a thunk that calls `ProcessEvent` to execute the overridden body.
* You'll need to add the `BlueprintCallable` keyword if you want to call this function from Blueprint, otherwise it's only callable via C++.

```cpp
UFUNCTION(BlueprintImplementableEvent)
void OnSomethingHappened();
```

### BlueprintNativeEvent

This function is designed to be overridden in Blueprint, but also has a native (C++) implementation.

* To create a native implementation of the function, you'll need to define a method named `[FunctionName]_Implementation` instead of just the function name. This is due to how the auto-generated code will include a thunk that calls the implementation method when necessary.
* You'll need to add the `BlueprintCallable` keyword if you want to call this function from Blueprint, otherwise it's only callable via C++.

{% tabs %}
{% tab title="Example.h" %}

```cpp
UFUNCTION(BlueprintNativeEvent)
void DoSomething();
```

{% endtab %}

{% tab title="Example.cpp" %}

```cpp
void Example::DoSomething_Implementation() {
    // Your code here
}
```

{% endtab %}
{% endtabs %}

### **BlueprintPure**

The function does not affect the owning object in any way and can be executed in a Blueprint.

* It's effectively the same as marking a method as `BlueprintCallable` with the `const` C++ keyword.
* These functions must have a return type.
* It is not required, but generally recommended that the function be marked `const`.

```cpp
UFUNCTION(BlueprintPure)
float GetValue() const;
```

### **BlueprintSetter**

&#x20;This function will be used as the mutator for a Blueprint-exposed property. This specifier implies `BlueprintCallable`.

> More information needed about this keyword.

### CallInEditor

This function can be called in the editor on selected instances via a button in the Details panel.

> More information needed about this keyword.

### **Category**

Specifies the category of the function when displayed in Blueprint editing tools.&#x20;

* You can define nested categories using the `|` operator.
* Quotes are only required when adding spaces or the `|` operator.

```cpp
UFUNCTION(BlueprintCallable, Category="Weapon|Gun")
void Fire();
```

### **Client**

&#x20;The function is only executed on the client that owns the Object on which the function is called. See [Unreal's documentation on RPCs](https://docs.unrealengine.com/en-US/Gameplay/Networking/Actors/RPCs/index.html) for more information.

* Declares an additional function named the same as the main function, but with `_Implementation` added to the end. The auto-generated code will call the `_Implementation` method when necessary.
* Owning client is the object with `ENetRole` of `AutonomousProxy`.
* RPC functions should not have a return value.
* RPC functions are unreliable by default.

```cpp
UFUNCTION(Client)
void ReportHit(float Damage, FVector Direction);
```

### **Custom Thunk**

The `UnrealHeaderTool` code generator will not produce a thunk for this function; it is up to the user to provide one.

> More information needed about this keyword.

### **Exec**

This function is executable from the command line. For more information, [check out this wiki article about the Exec Functions](/4.25/wiki-archives/common-pitfalls/exec-functions).

```cpp
UFUNCTION(Exec)
void GodMode(bool bEnabled);
```

### NetMulticast

&#x20;The function is executed both locally on the server, and replicated to all clients, regardless of the Actor's `NetOwner`. See [Unreal's documentation on RPCs](https://docs.unrealengine.com/en-US/Gameplay/Networking/Actors/RPCs/index.html) for more information.

* Declares an additional function named the same as the main function, but with `_Implementation` added to the end. The auto-generated code will call the `_Implementation` method when necessary.
* Multicast RPCs behave differently when called by the network authority (server) or client:
  * If they are called from the server, the server will execute them locally as well as execute them on all currently connected clients.
  * If they are called from clients, they will only execute locally, and will not execute on the server.
* Multicast functions are throttled and will not replicate more than twice in a given Actor's network update period.
* RPC functions should not have a return value.
* RPC functions are unreliable by default.

```cpp
UFUNCTION(NetMulticast)
void BroadcastGameplayEvent(EGameplayEventType EventType);
```

### **Reliable**

The function is replicated over the network, and is guaranteed to arrive regardless of bandwidth or network errors. Only valid when used in conjunction with the `Client` or `Server` keywords.

```cpp
UFUNCTION(Client, Reliable)
void SendPrivateMessage(FString Text);
```

### **SealedEvent**

&#x20;This function cannot be overridden in sub-classes. The `SealedEvent` keyword can only be used for events. For non-event functions, declare them as `static` or `final` to seal them.

```cpp
UFUNCTION(BlueprintNativeEvent, SealedEvent)
void DoSomething();
```

### **ServiceRequest**

This function is an RPC (Remote Procedure Call) service reques&#x74;**.**

> More information needed about this keyword.

### ServiceResponse

This function is an RPC service response.

> More information needed about this keyword.

### **Server**

&#x20;The function is only executed on the server. See [Unreal's documentation on RPCs](https://docs.unrealengine.com/en-US/Gameplay/Networking/Actors/RPCs/index.html) for more information.

* Declares an additional function named the same as the main function, but with `_Implementation` added to the end, which is where code should be written. The auto-generated code will call the `_Implementation` method when necessary.
* The `WithValidation` keyword must be used with the `Server` keyword.
* RPC functions should not have a return value.
* RPC functions are unreliable by default.

```cpp
UFUNCTION(Server, WithValidation)
void ServerSendInputValue(float Value);
```

### **Unreliable**

The function is replicated over the network but can fail due to bandwidth limitations or network errors.&#x20;

* Only valid when used in conjunction with `Client` or `Server`.

```cpp
UFUNCTION(Client, Unreliable)
void SendObjectLocation(FVector Location);
```

### **WithValidation**

Declares an additional function named the same as the main function, but with `_Validate` added to the end. This function takes the same parameters, and returns a `bool` to indicate whether or not the call to the main function should proceed.

* Required for the `Server` keyword. This was done to encourage secure server RPC functions, and to make it as easy as possible for someone to add code to check each and every parameter to be valid against all the known input constraints.

{% tabs %}
{% tab title="MyCharacter.h" %}

```cpp
UFUNCTION(Server, Reliable, WithValidation)
void ServerSetSprint(bool bSprinting);
```

{% endtab %}

{% tab title="MyCharacter.cpp" %}

```cpp
void AMyCharacter::ServerSetSprint_Implementation(bool bSprinting) {
  SetSprint(bSprinting);
}

bool AMyCharacter::ServerSetSprint_Validate(bool bSprinting) {
  return true;
}
```

{% endtab %}
{% endtabs %}

## Additional Resources

* [Unreal Official Documentation: UFunctions](https://docs.unrealengine.com/en-US/Programming/UnrealArchitecture/Reference/Functions/index.html)
* [Tom Looman: UFUNCTION Keywords Explained](https://www.tomlooman.com/ue4-ufunction-keywords-explained/)


# Wiki Archives

Epic's choice to take down the wiki came quick. This guide hopes to help developers looking for the content that used to be found on Epic's now defunct Wiki.

## So the community Wiki is gone, now what?

~~It would be shocking if Epic didn't wind up putting the Wiki back only, at least for a temporary amount of time. But in the event that they don't (or if it takes them a while to do so), we can do our best to retain and archive as much of the wiki on this site.~~

![](https://media.giphy.com/media/8qr5b7fs7JqxrvEOzH/giphy.gif)

Since this news broke a number of things have happened and this page was first created, a number of things have happened. As a result, this guidebook will become more of a resource manual that offers guidance of a focused set of topics that will independently maintained by a smaller group of developers.

### A new community-driven wiki was launched for Unreal Engine 4

A **community** effort has been launched to create a new wiki resource for developers. You can check out the new wiki using the link below. Heads up though, it's still in a work in progress!

{% embed url="<https://ue4community.wiki>" %}

In addition to the new wiki, there's a community driven Discord channel around this effort. We'd love to have anyone looking to contribute to the conversation around building a better platform for Unreal Engine and game development knowledge-share.

{% embed url="<https://discord.gg/GsEw5z4>" %}

### Epic released a static file dump of the wiki contents

One of Epic's community managers reached out to us (the community mentioned above) and provided access to an archive of all the original wiki files. It's hosted on Box and you can access it using the link below. If you can't find the article you're looking for on the new wiki, or want the original version of the content, then that's going to be the place to look.

{% embed url="<https://epicgames.ent.box.com/s/2e5hhlvqyu9octooxbkgwt2xdmmrea9z>" %}

### Other members of the community started publishing their own archives

Several other members have created solutions for getting the old wiki content online. For example, [Michael Cole](https://github.com/michaeljcole) did a great job of building a quick Github pages solution using the Wayback Machine archive content.

{% embed url="<https://michaeljcole.github.io/wiki.unrealengine.com/>" %}

### I can't find the article I'm looking for...

We've gone ahead and scoured the Wayback Machine in order to a create a `.zip` file with as much archival data as we could retrieve. This file is available for download on Dropbox using the following link:

{% embed url="<https://www.dropbox.com/s/g7plgzei399v342/wiki.unrealengine.com.zip?dl=0>" %}

If you can't find it in the `.zip` archive, changes are that it's lost for good until Epic or the original author reposts it somewhere else.


# Debugging & Utilities


# Exec Functions

### Overview

Exec functions are pretty cool and super useful, especially in development. They let you call functions from the command line. The crappy part is they are poorly documented and have a lot of caveats and hidden functionality, so I wanted to make this page as a catching point until the exec documentation gets better.

### What Are They?

So what are exec functions. Pretty much exec functions are a simple way to declare console accessible functions through the UFUNCTION macro system easily by just adding the "Exec" command. The console commands kind of cascade their way down through either the player controllers or viewport until they are handled at some point in the chain.

They're called simply from the console by pressing the \~ key on most keyboards and typing the name of your function with any arguments entered after.

### What Classes Can Have Exec Functions?

Only some classes support Exec functions out of the box. Possessed Pawns, Player Controllers, Player Input, Cheat Managers, Game Modes, Game Instances, overriden Game Engine classes, and Huds should all work by just adding the standard UFUNCTION markup. Exec functions tend to cascade down to these classes through the player controller (Pawn/Player Controllers/Cheat Manager/etc.) or the game viewport (game instance/game mode/etc). If there is something amiss with either of those, you will probably run into issues with your exec functions running at all.

There are some other classes that are supported out of the box, but they're mostly other ways of getting to the above classes and are probably better to avoid if you don't know what you're doing.

As far as how to support classes that aren't supported out of the box, see the section below on how to support exec functions in classes that don't natively support them.

### How Do I Declare Them?

Declaring an exec function is super simple.

```cpp
   UFUNCTION(Exec)
   void YourExecFunction();
```

Called just by entering it in the command line like so:

![](https://web.archive.org/web/20191020173554im_/https://d26ilriwvtzlb.cloudfront.net/e/ed/ExecFuncNoArg.PNG)

Adding arguments is also simple.

```cpp
   UFUNCTION(Exec)
   void YourExecFunction(int32 arg1, FString arg2);
```

With your arguments separated by spaces.

![ExecFuncWithArgs.PNG](https://web.archive.org/web/20191020173554im_/https://d26ilriwvtzlb.cloudfront.net/4/4a/ExecFuncWithArgs.PNG)

### How Do I Get Other Classes to Support Exec Functions?

So the main reason I wanted to write this up was because of this cool feature. It's possible to get Exec functions working on any UObject class you want. The only caveat is that you need to make sure an instance of that object is somehow accessible from one of the classes above. Preferably you'll want only one instance of that class to be accessible from above. I use this mostly just to keep classes from becoming overcrowded with exec functions that just pipe the call to a member anyway. It's really easy to fall into the trap of having one class be an exec function dumping ground for your whole game.

Anyway, how do you do it? This is actually also really simple. The unreal header tool does most of the footwork generating the Exec function's metadata already, so all you really need to do is forward the ProcessConsoleExec function from an Exec capable class to an instance of the class you want to call Exec functions on under it.

In the header:

```cpp
   virtual bool ProcessConsoleExec(const TCHAR* Cmd, FOutputDevice& Ar, UObject* Executor) override;
```

In the cpp:

```cpp
   bool YourExecCapableClass::ProcessConsoleExec(const TCHAR* Cmd, FOutputDevice& Ar, UObject* Executor)
   {
       bool handled = Super::ProcessConsoleExec(Cmd, Ar, Executor);
       if (!handled)
       {
               handled &= _yourNewExecInstance->ProcessConsoleExec(Cmd, Ar, Executor);
       }
       return handled;
   }
```

You shouldn't even have to override anything on your new class because the processing is handled by the UObject interface. All you have to do is call it.


# How To Prevent Crashes Due To Dangling Actor Pointers

This wiki article was written by Rama.

While working on Abatron, an RTS/FPS hybrid game with tons of character units to keep track of, I created a lot of arrays of Actors:

```cpp
TArray<AActor*> UnitArray;
```

During multiplayer testing especially, stale / dangling AActor pointers were causing a lot of crashes!

The problem with stale pointers is that just checking ActorPtr != nullptr is not enough, a stale pointer will return true but wont actually still be pointing to a valid AActor, which is what causes the crash.

### UPROPERTY() UObjects Clear References Properly

A less-advertised feature of UObject pointers that are made UPROPERTY() is that they are properly updated to NULL when the object is destroyed, unlike raw pointers like I was using above.

Automatic Updating of UObject References <https://docs.unrealengine.com/latest/INT/Programming/UnrealArchitecture/Objects/Optimizations/index.html#automaticupdatingofreferences>

So the **simple solution** if you are having issues with dangling / stale actor pointers is to make sure all AActor pointers are marked with UPROPERTY().

```cpp
UPROPERTY() //<~~~ That's it! This now makes the pointers much more stable! -Rama
TArray<AActor*> UnitArray;
```

### TWeakObjectPtr

For UObjects especially, having lots of UPROPERTY() references to them can prevent them from getting garbage collected properly. For this situation you can use TWeakObjectPtr which will still give you additional validity option using IsValid() but will not prevent GC from running.

### Conclusion

If you are encountering AActor\* pointers that are going stale and crashing your game, make sure they are marked with UPROPERTY() and you will be taking advantage of a rather essential feature of UObjects in UE4, which is that all UPROPERTY() references get updated to NULL when a UObject is destroyed.

Have fun today!

Rama


# Profiling: How to Count CPU Cycles

This wiki article was written by Rama.

## Overview

In this wiki I show you how you can count the CPU cycles of individual blocks of your game code, and expose this information to a very easy-to-use UI in the UE4 Editor! This wiki shows you how to leverage all the work Epic engineers have put into the UE4 profiler, customizing it to monitor named sections of your game code! After you're done with this wiki you will be able to check on the performance of any individual lines or functions from your entire project-level code base, assigning your own chosen names to these blocks of code! Enjoy! Rama

### Pic of What This Wiki Enables You To Do

![We have our own stats now](https://3425263208-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M3mx7Lszp8LdwKKD7yR%2F-M462J1RJdKu8dvwBJxs%2F-M462MQGxvvXIZuKznIE%2FWeHaveOurOwnStatsNow.jpg?generation=1586035009073238\&alt=media)

In this picture you can see I've created my own custom STAT so that the UE4 Profiler can track a specific block of my game code that I called **"Joy \~ PerformSphereMovement"**.

I've successfully tracked the CPU cycles of a section of my own project-level code base and exposed this information to the very friendly GUI of the UE4 Profiler!

Yay!

This picture shows that the UE4 Profiler has confirmed my guess that a certain block of my code was causing almost 97% (96.6) of the performance hit for all the character tick code in my entire code base!

It saves me hours of time to be able to easily narrow down what block of code in my rather large character code base is causing **literally 97% of the character-code performance hit!**

### UE4 Documentation on the Profiler

I assume you are familiar with the basics of the UE4 profiler in this tutorial.

If you have not yet seen what the profiler can already do for you, I recommend reading the Epic Documentation and trying it out!

[Epic Documentation on the Amazing UE4 Profiler](https://docs.unrealengine.com/en-US/Engine/Performance/Profiler/index.html)

### Running The UE4 Profiler

Type in the in-game console to Start Profile:

```
 "stat startfile";
```

Type in the in-game console To Stop Profile

```
 "stat stopfile";
```

### Opening Your Profiled Game Session Data in the Editor

Go to Window->Developer Tools->Session Front End

Then click on the profiler button!

![Session Frontend](https://3425263208-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M3mx7Lszp8LdwKKD7yR%2F-M462J1RJdKu8dvwBJxs%2F-M462MQJlVn4mAOZwhPK%2FSessionFrontProfiler.jpg?generation=1586035010002378\&alt=media)

Then you can load your file that you saved!

It will be under the Saved/Profiling directory :)

Always check the date to make sure you are looking at the right file!

### Self

Now on to the core of this wiki!

You'll notice that in your game code there will be huge blocks called "Self" which indicates code that has not been divided up into cycle-counted sub-sections! This Self block is all of the code running for your in-game class instances.

Well here is how you can sub-divide Self into your own chosen named categories, neatly organizing and cateloging your own code base!

### Creating Your Own Stat Group

Let's say you have class hierachy of classes for your in-game Character.

You want to subdivide the inner workings of your entire character code into CPU cycle-counted code blocks.

In the highest level of your class structure, in the .h, declare your category

```cpp
//For UE4 Profiler ~ Stat Group
DECLARE_STATS_GROUP(TEXT("JoyBall"), STATGROUP_JoyBall, STATCAT_Advanced);
```

### Creating the Stat

In the .cpp where you want to track a particular function body, put this at the top just below the #includes

```cpp
/*
    By Rama
*/
#include "Joy.h"
#include "JoyBall.h"

//For UE4 Profiler ~ Stat
DECLARE_CYCLE_STAT(TEXT("Joy ~ PerformSphereMovement"), STAT_PerformSphereMovement, STATGROUP_JoyBall);
```

Please note you can create as many CYCLE\_STAT's as you want for your particular STATGROUP !

And you should have one DECLARE\_CYCLE\_STAT for each function body/scope that you want to count cycles for.

### Using the Stat

At the very top of the scope of the function you want to track, put the SCOPE macro. Everything within the brackets of the scope you put the SCOPE\_CYCLE\_COUNTER in will be cycle-counted by the profiler!

```cpp
void AJoyBallMovement::PerformSphereMovement()
{
    SCOPE_CYCLE_COUNTER(STAT_PerformSphereMovement);

    //... your code that you want to test the performance of and have show up in the profiler

} //Cycle count scope ends here -Rama
```

### Counting CPU Cycles For Any Block of Code

Please note your scope can be within a single function, just make sure to give such a stat an appropriate name like YourFunction\_Internal or something Again, the SCOPE\_CYCLE\_COUNTER will cycle-count within its brackets

```cpp
void AJoyBallMovement::PerformSphereMovement()
{
    //First part of this function, code that wont be cycle counted
    ConsoleCommand("Joy");
    //... etc

    //You can scope any lines of code you want by adding brackets!
    {
        SCOPE_CYCLE_COUNTER(STAT_PerformSphereMovement);
        int32 Parameter = 200;
        YourFunctionThatYouThinkMightBeSlow(Parameter);
        //other code to cycle count

    } //Cycle count scope ends here -Rama


    //More code that wont be cycle counted
    ConsoleCommand("~~~~~");
        //... etc
}
```

### Example From My Code Base

See the picture in the overview!

In my own code base I had a 10 class inheritance hierarchy for my game character, and the UE4 profiler was simply telling me that the character "Self" was costing 37% of my total performance hit.

I used the info I am sharing with you in this wiki to create a SCOPE\_CYCLE\_COUNTER for the function that I thought was probably taking all the performance, and I was right!

But the most important thing is that I enabled the awesome UE4 Profiler to help me narrow down the performance hit in my game code to just a single function / block of code, and so with that info I can easily address the performance hit, knowing it is worth the effort to rewrite the code!

### Conclusion

You now know how you can CPU cycle-count individual lines of your game code base, and expose this information to UE4's super awesome GUI Profiler!

Enjoy!


# Logs: Printing Messages to Yourself during Runtime

This wiki article was written by Rama; Converted by jfaw.

## Overview

Dear Community,

Logs are essential for giving yourself feedback as to whether

* Your new functions are even being called
* What data your algorithm is using during runtime
* Reporting errors to yourself and the end user / debugging team
* Imposing a fatal error to stop runtime execution in special circumstances

This page describes how to use the **Unreal output log**.

Other options are also discussed at the bottom of the page.

## Accessing Logs

### In-Game

To see logs you must run your game with `-Log` (you must create a shortcut to the Editor executable and add `-Log` to the end).

or use console command "showlog" in your game.

### Within Editor (Play-In-Editor)

Log messages are sent to the 'Output' log which is accessible via *Window -> Developer Tools -> Output Log*.

If you are using the Editor and PIE, logging should be enabled by default due to the presence of `GameCommandLine=-log` in your Engine INI file. If no logging is visible, add the `-Log` command line option as per the instructions for In-Game logging above.

### Quick Usage

```cpp
UE_LOG(LogTemp, Warning, TEXT("Your message"));
```

This way you can log without the need of creating a custom category. Doing so will keep everything clean and sorted though.

### Log Verbosity Levels

Log verbosity levels are used to more easily control what is being printed, allowing you to keep even the most detailed log statements in your code without having them spam output when you don't want them to. Each log statement declares which log it belongs to and it's verbosity level. Verbosity level is controlled on a per-log basis.

Each log's verbosity is controlled by four things: 1. Compile-time verbosity 2. Default verbosity 3. `.ini` verbosity 4. Runtime-verbosity.

If a log statement is more verbose than it's log's compile time verbosity it won't even be compiled into the game code. From there the log's level is set to the default verbosity, which can then be overridden in the Engine.ini file, either of those can then be overridden from the command line (the runtime verbosity). Once the game (or editor) is running it may not be possible to change a log category's verbosity (I am not sure, someone who knows please correct this).

Here are the verbosity levels available to use:

* **Fatal** Fatal level logs are always printed to console and log files and crashes even if logging is disabled.
* **Error** Error level logs are printed to console and log files. These appear red by default.
* **Warning** Warning level logs are printed to console and log files. These appear yellow by default.
* **Display** Display level logs are printed to console and log files.
* **Log** Log level logs are printed to log files but not to the in-game console. They can still be viewed in editor as they appear via the Output Log window.
* **Verbose** Verbose level logs are printed to log files but not the in-game console. This is usually used for detailed logging and debugging.
* **VeryVerbose** VeryVerbose level logs are printed to log files but not the in-game console. This is usually used for very detailed logging that would otherwise spam output.

For the `CompileTimeVerbosity` parameter of `DECLARE_LOG_CATEGORY_EXTERN` it is also valid to use `All` (functionally the same as using `VeryVerbose`) or `NoLogging` (functionally the same as using `Fatal`).

## Setting Up Your Own Log Category

### Log Category Macros

The macros `DECLARE_LOG_CATEGORY_EXTERN` and `DEFINE_LOG_CATEGORY` go in *YourGame.h* and *YourGame.cpp* respectively.

The macro to declare a log category has three parameters. Each declared log category should have a corresponding defined log category in a cpp.

```cpp
DECLARE_LOG_CATEGORY_EXTERN(CategoryName, DefaultVerbosity, CompileTimeVerbosity);
```

`CategoryName` is simply the name for the new category you are defining.

`DefaultVerbosity` is the verbosity level used when one is not specified in the ini files or on the command line. Anything more verbose than this will not be logged.

`CompileTimeVerbosity` is the maximum verbosity to compile in the code. Anything more verbose than this will not be compiled.

The macro to define a log category takes only the name of the category.

```cpp
DEFINE_LOG_CATEGORY(CategoryName);
```

### Usage Example

You can have different log categories for different aspects of your game!

This gives you additional info, because `UE_LOG` prints out which log category is displaying a message.

Here is an example of where the different log levels start to become useful.

Say you're often having trouble with a certain system in your game. In debugging you might want very detailed logs, but when you've finished debugging for now you know you might need those detailed logs later on, but they're spamming the output. What do you do? Use different log levels.

#### MyGame.H

```cpp
//General Log
DECLARE_LOG_CATEGORY_EXTERN(LogMyGame, Log, All);

//Logging during game startup
DECLARE_LOG_CATEGORY_EXTERN(LogMyGameInit, Log, All);

//Logging for your AI system
DECLARE_LOG_CATEGORY_EXTERN(LogMyGameAI, Log, All);

//Logging for a that troublesome system
DECLARE_LOG_CATEGORY_EXTERN(LogMyGameSomeSystem, Log, All);

//Logging for Critical Errors that must always be addressed
DECLARE_LOG_CATEGORY_EXTERN(LogMyGameCriticalErrors, Log, All);
```

#### MyGame.CPP

```cpp
#include "MyGame.h"

//General Log
DEFINE_LOG_CATEGORY(LogMyGame);

//Logging during game startup
DEFINE_LOG_CATEGORY(LogMyGameInit);

//Logging for your AI system
DEFINE_LOG_CATEGORY(LogMyGameAI);

//Logging for some system
DEFINE_LOG_CATEGORY(LogMyGameSomeSystem);

//Logging for Critical Errors that must always be addressed
DEFINE_LOG_CATEGORY(LogMyGameCriticalErrors);
```

#### MyClass.CPP

```cpp
//...
void UMyClass::FireWeapon()
{
    UE_LOG(LogMyGameSomeSystem, Verbose, TEXT("UMyClass %s entering FireWeapon()"), *GetNameSafe(this));
    //Logic
    UE_LOG(LogMyGameSomeSystem, Verbose, TEXT("UMyClass %s Attempting to fire."), *GetNameSafe(this));
    if (CheckSomething())
    {
        UE_LOG(LogMyGameSomeSystem, Log, TEXT("UMyClass %s is firing their weapon with charge of %f"), *GetNameSafe(this), GetCharge());
        //Firing logic
    }
    else
    {
        UE_LOG(LogMyGameSomeSystem, Error, TEXT("UMyClass %s CheckSomething() returned false during FireWeapon(), this is bad!"), *GetNameSafe(this));
        //Fail with grace
    }
    //More code!
    UE_LOG(LogMyGameSomeSystem, Verbose, TEXT("UMyClass %s leaving FireWeapon()"), *GetNameSafe(this));
}

void UMyClass::Tick(float DeltaTime)
{
    UE_LOG(LogMyGameSomeSystem, VeryVerbose, TEXT("UMyClass %s's charge is %f"), *GetNameSafe(this), GetCharge());
    if (something)
    {
        UE_LOG(LogMyGameSomeSystem, VeryVerbose, TEXT("Idk"));
    }
    if (somethingelse)
    {
        UE_LOG(LogMyGameSomeSystem, VeryVerbose, TEXT("Stuff"));
    }
}
//...
```

When you're not working on this system all these log statements would absolutely flood your output, and even when you are working on it you might not want the level of detail that is putting out multiple logs per tick.

By using log levels you can simply change the verbosity in the category's declaration, in the ini files, or on the command line to hide/reveal different layers of log statements as you need them. Ex:

```cpp
//All log statements are shown.
DECLARE_LOG_CATEGORY_EXTERN(LogMyGameSomeSystem, Log, All);

//VeryVerbose statements won't be shown.
DECLARE_LOG_CATEGORY_EXTERN(LogMyGameSomeSystem, Verbose, All);

//Neither VeryVerbose nor Verbose statements will be shown.
DECLARE_LOG_CATEGORY_EXTERN(LogMyGameSomeSystem, VeryVerbose, All);
```

The log categories used by Unreal Engine use different log levels, but by default have a higher `CompileTimeVerbosity`. In debugging interaction with Unreal code it might be helpful to turn up the verbosity of Unreal code in *DefaultEngine.ini* under `[Core.Log]` by adding an entry like `LogOnline=Verbose`.

## Log Formatting

#### Log Message

```cpp
//"This is a message to yourself during runtime!"
UE_LOG(YourLog,Warning,TEXT("This is a message to yourself during runtime!"));
```

#### Log an FString

* `%s` strings are wanted as `TCHAR*` by `Log`, so use `*FString()`

```cpp
//"MyCharacter's Name is %s"
UE_LOG(YourLog,Warning,TEXT("MyCharacter's Name is %s"), *MyCharacter->GetName() );
```

#### Log an Bool

```cpp
//"MyCharacter's Bool is %s"
UE_LOG(YourLog,Warning,TEXT("MyCharacter's Bool is %s"), (MyCharacter->MyBool ? TEXT("True") : TEXT("False")));
```

#### Log an Int

```cpp
//"MyCharacter's Health is %d"
UE_LOG(YourLog,Warning,TEXT("MyCharacter's Health is %d"), MyCharacter->Health );
```

#### Log a Float

```cpp
//"MyCharacter's Health is %f"
UE_LOG(YourLog,Warning,TEXT("MyCharacter's Health is %f"), MyCharacter->Health );
```

#### Log an FVector

```cpp
//"MyCharacter's Location is %s"
UE_LOG(YourLog,Warning,TEXT("MyCharacter's Location is %s"), 
    *MyCharacter->GetActorLocation().ToString());
```

#### Log an FName

```cpp
//"MyCharacter's FName is %s"
UE_LOG(YourLog,Warning,TEXT("MyCharacter's FName is %s"), 
    *MyCharacter->GetFName().ToString());
```

#### Log an FString,Int,Float

```cpp
//"%s has health %d, which is %f percent of total health"
UE_LOG(YourLog,Warning,TEXT("%s has health %d, which is %f percent of total health"),
    *MyCharacter->GetName(), MyCharacter->Health, MyCharacter->HealthPercent);
```

## Log Coloring

#### Log: Grey

```cpp
//"this is Grey Text"
UE_LOG(YourLog,Log,TEXT("This is grey text!"));
```

#### Warning: Yellow

```cpp
//"this is Yellow Text"
UE_LOG(YourLog,Warning,TEXT("This is yellow text!"));
```

#### Error: Red

```cpp
//"This is Red Text"
UE_LOG(YourLog,Error,TEXT("This is red text!"));
```

#### Fatal: Crash for Advanced Runtime Protection

You can throw a fatal error yourself if you want to make sure that certain code never runs.

I have used this myself to help protect against algorithm cases that I wanted to make sure never occurred again.

It's actually really useful!

But it does look like a crash, and so if you use this, dont be worried, just look at the crash call stack :)

* Again this is an advanced case that crashes the program, **use only for extremely important circumstances**.

```cpp
//some complicated algorithm
if(some fringe case that you want to tell yourself if the runtime execution ever reaches this point)
{
    //"This fringe case was reached! Debug this!"
    UE_LOG(YourLog,Fatal,TEXT("This fringe case was reached! Debug this!"));
}
```

## Quick tip print

This a trick for easy print debug, you can use this MACRO at the begin of your cpp

```cpp
#define print(text) if (GEngine) GEngine->AddOnScreenDebugMessage(-1, 1.5, FColor::White,text)
```

then you can use a regular lovely `print();` inside to all.

To prevent your screen from being flooded, you can change the first parameter, key, to a positive number. Any message printed with that key will remove any other messages on screen with the same key. This is great for things you want to log frequently.

## Other Options for Debugging

### Logging message to the screen

For the times when you want to just display the message on the screen, you can also do:

```cpp
 #include <EngineGlobals.h>
 #include <Runtime/Engine/Classes/Engine/Engine.h>
 // ...
 GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, TEXT("This is an on screen message!"));
 GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, FString::Printf(TEXT("Some variable values: x: %f, y: %f"), x, y));
```

To prevent your screen from being flooded, you can change the first parameter, key, to a positive number. Any message printed with that key will remove any other messages on screen with the same key. This is great for things you want to log frequently.

### Logging message to the \~ Client Console

Pressing the `~` key in Unreal brings up the client console.

If you use the `PlayerController` class you can print a message to this console, which has the advantage of being a completely different logging space which does not require tabbing out of the game to view easily

```cpp
 PC->ClientMessage("Your Message");
```

* [Answerhub post on using `ClientMessage`](https://answers.unrealengine.com/questions/81662/vshow-function.html):
* [Forum Post on post messages to the client console](https://forums.unrealengine.com/showthread.php?33367-Log-to-Console%7Csend)

## Log conventions (in the console, ini files, or environment variables)

* \[cat] = a category for the command to operate on, or 'global' for all categories.
* \[level] = verbosity level, one of: none, error, warning, display, log, verbose, all, default

At boot time, compiled in default is overridden by ini files setting, which is overridden by command line

## Log console command usage

* `Log list` - list all log categories
* `Log list [string]` - list all log categories containing a substring
* `Log reset` - reset all log categories to their boot-time default
* `Log [cat]` - toggle the display of the category \[cat]
* `Log [cat] off` - disable display of the category \[cat]
* `Log [cat] on` - resume display of the category \[cat]
* `Log [cat] [level]` - set the verbosity level of the category \[cat]
* `Log [cat] break` - toggle the debug break on display of the category \[cat]

## Log command line

* `-LogCmds=\"[arguments],[arguments]...\"` - applies a list of console commands at boot time
* `-LogCmds=\"foo verbose, bar off\"` - turns on the foo category and turns off the bar category

## Environment variables

Any command line option can be set via the environment variable **UE-CmdLineArgs**

`set UE-CmdLineArgs=\"-LogCmds=foo verbose breakon, bar off\"`

## Config file

In *DefaultEngine.ini* or *Engine.ini*:

```
[Core.Log]
global=[default verbosity for things not listed later]
[cat]=[level]
foo=verbose break
```

♥ -Rama


# Macros & Data Types


# Structs, USTRUCTS(), They're Awesome

Guide on using USTRUCTS by Rama the legend

### Overview

**Original Author: Rama**

Structs enable you to create custom variable types to organize your data, by relating other c++ or UE4 C++ data types to each other.

The power of structs is extreme organization, as well as ability to have functions for internal data type operations!

#### Technical

Structs enable you to create custom variable types to organize your data, by relating other C++ or UE4 C++ data types to each other. The power of structs is extreme organization as well as the ability to have functions for internal data type operations. '

In UE4, structs should be used for simple data type combining and data management purposes. For complex interactions with the game world, you should make a `UObject` or `AActor` subclass instead.

### Core Syntax

```cpp
//If you want this to appear in BP, make sure to use this instead //USTRUCT(BlueprintType)
USTRUCT() struct FJoyStruct
{
    GENERATED_BODY()

    // Always make USTRUCT variables into UPROPERTY()
    // any non-UPROPERTY() struct vars are not replicated

    // So to simplify your life for later debugging, always use UPROPERTY()
    UPROPERTY()
    int32 SampleInt32;

    //If you want the property to appear in BP, make sure to use this instead
    //UPROPERTY(BlueprintReadOnly)

    UPROPERTY()
    AActor* TargetActor;

    //Set
    void SetInt(const int32 NewValue)
    {
        SampleInt32 = NewValue; 
    }

    //Get
    AActor* GetActor()
    {
        return TargetActor;
    }

    //Check
    bool ActorIsValid() const
    {
        if(!TargetActor)
            return false;

        return TargetActor->IsValidLowLevel();
    }

    //Constructor
    FJoyStruct()
    {
        // Always initialize your USTRUCT variables!
        // exception is if you know the variable type has its own default 
        constructor SampleInt32 = 5;
        TargetActor = nullptr;
    } 
};
```

> **Additional Note Author: DesertEagle\_PWN**\
> The idea of USTRUCTS() is to declare engine data types that are in global scope and can be accessed by other classes/structs/blueprints. Because of this, it is invalid UE4 syntax to declare a struct inside of a class or other struct if using the USTRUCT() macro. Regular structs can still be utilized inside your classes and other structs; however these cannot be replicated natively and will not be available for UE4 reflective debugging or other engine systems such as Blueprints.
>
> **Additional Note Author: Darkgaze**\
> Concerning the variables visibility on the editor: In the example above, if you don't add "EditAnywhere" parameter into UPROPERTY inside the members of the USTRUCT, whey won't show up in the Editor panel. You will see the variable but there will be no way to see/change/unfold the values inside. The class that defines a new UPROPERTY using that struct type should have that parameter too. In case you can't modify the data and you are using blueprints, you should add BlueprintType inside the USTRUCT parenthesis.

### Examples

#### Example 1

You want to relate a float brightness value with a world space location FVector, both of which are interpolated using an Alpha value.

And you want to do this for 100 different game locations simultaneously. And you want to do this process repeatedly over time! You need to store the incremental interpolation values between game events. AActors/UObjects are not involved (You could just subclass `AActor`/`UObject` and store the data per instance)

```cpp
USTRUCT()
struct FMyInterpStruct
{
    GENERATED_BODY()

    UPROPERTY()
    float Brightness;

    UPROPERTY()
    float BrightnessGoal; //interping to

    UPROPERTY()
    FVector Location;

    UPROPERTY()
    FVector LocationGoal;

    UPROPERTY()
    float Alpha;


    void InterpInternal()
    {
        Location = FMath::Lerp<FVector>(Location,LocationGoal,Alpha);
        Brightness = FMath::Lerp<float>(Brightness,BrightnessGoal,Alpha);
    }

    //Brightness out is returned, FVector is returned by reference 
    float Interp(const float& NewAlpha, FVector& Out)
    { 
        // value received from rest of your game engine
        Alpha = NewAlpha;

        //Internal data structure management
        InterpInternal();

        //Return Values
        Out = Location;
        return Brightness;
    }

    FMyInterpStruct()
    {
        Brightness = 2;
        BrightnessGoal = 100;
        Alpha = 0;
        Location = FVector::ZeroVector;
        LocationGoal = FVector(0,0,200000);
    } 
};
```

#### Example 2

You want to track information about particle system components that you have spawned into the world through

```cpp
UGameplayStatics::SpawnEmitterAtLocation() // returns a UParticleSystemComponent
```

and you want to track the lifetime of the particle and apply parameter changes from C++. You could write your own class, but if your needs are simple or you do not have project-permissions to make a subclass of `UParticleSystemComponent`, you can just make a `USTRUCT` to relate the various data types!

```cpp
USTRUCT()
struct FParticleStruct
{
    GENERATED_BODY()

    UPROPERTY()
    UParticleSystemComponent* PSCPtr;

    UPROPERTY()
    float LifeTime;


    void SetColor()
    {
        // your code here
    }

    FLinearColor GetCurrentColor() const
    {
        // your code here
    }

    // For GC
    void Destroy()
    {
        PSCPtr = nullptr;
    }

    //Constructor
    FParticleStruct()
    {
        PSCPtr = nullptr;
        LifeTime = -1;
    }
};
```

**Particle Data Tracker**

Now you can have an array of these `USTRUCTS` for each particle that you spawn!

```cpp
// Particle Data Tracking Array
UPROPERTY()
TArray<FParticleStruct> PSCArray;
```

**Garbage Collection**

By marking a `USTRUCT` or `USTRUCT` array as `UPROPERTY()` and marking any UObject / AActor members as `UPROPERTY()`, you are protected from dangling pointer crashes

[link to article](https://app.gitbook.com/s/-M3mx7Lszp8LdwKKD7yR-3772691856/wiki-archives/macros-and-data-types/How_To_Prevent_Crashes_Due_To_Dangling_Actor_Pointers)

However you must also clear ustructs you no longer need if they have pointers to `UObjects` if you ever want GC to be able garbage collect those `UObjects`.

### Structs With Struct Member Variables

The struct that wants to use another struct must be defined below the struct it wants to include.

```cpp
USTRUCT()
struct FFlowerStruct
{
    GENERATED_BODY()

    UPROPERTY()
    int32 NumPetals;

    UPROPERTY()
    FLinearColor Color;

    UPROPERTY()
    FVector Scale3D;

    void SetFlowerColor(const FLinearColor& NewColor)
    {
        Color = NewColor;
    }

    FFlowerStruct()
    {
        NumPetals = 5;
        Scale3D = FVector(1,1,1);
        Color = FLinearColor(1,0,0,1);
    }
};

USTRUCT()
struct FIslandStruct
{
    GENERATED_BODY()

    UPROPERTY()
    int32 Type;

    UPROPERTY()
    TArray<FVector> StarLocations;

    UPROPERTY()
    float RainAlpha;

    //Dynamic Array of Flower Custom USTRUCT()
    UPROPERTY() 
    TArray<FFlowerStruct> FlowersOnThisIsland;


    void SetRainAlpha(const float& NewAlpha)
    {
        RainAlpha = NewAlpha;
    }

    int32 GetStarCount() const
    {
        return StarLocations.Num();
    }

    FIslandStruct()
    {
        Type = 0;
        Percent = 1;
    }
};
```

### Struct Assignment

My personal favorite thing about structs is that unlike `UObject` or `AActor` classes, which must be utilized via pointers (`AActor*`) you can directly copy the entire contents of a `USTRUCT` to another `USTRUCT` of the same type with a single line of assignment!

```cpp
FFlowerStruct ExistingFlower;

// ... create ExistingFlower here

FFlowerStruct NewFlower;
NewFlower = ExistingFlower;
```

#### Deep Copy

If you have struct members pointing to UObjects or array pointers, you must be careful to copy these members yourself!

```cpp
USTRUCT()
struct FMyStruct
{
   int32* MyIntArray;
};

FMyStruct MyFirstStruct, MySecondStruct;

// Create the integer array on the first struct
MyFirstStruct.MyIntArray = new int32[10];
for( int i = 0; i < 10; ++i )
{
    MyFirstStruct.MyIntArray[i] = i;
}

GEngine->AddOnScreenMessage(-1, 10.f, FColor::Blue, FString::FromInt(MyFirstStruct.MyIntArray[4]));

// Assign the first struct to the second struct, i.e. create a shallow copy
MySecondStruct.MyIntArray[4] = 6;

GEngine->AddOnScreenMessage(-1, 10.f, FColor::Blue, FString::Printf(
    TEXT("%d %d"), MyFirstStruct.MyIntArray[4], MySecondStruct.MyIntArray[4]));
```

On screen the output will be

```
4
6 6
```

instead of the expected

```
4
4 6
```

This is because the data stored in `MyStruct::MyIntArray` is not actually stored inside of `MyStruct`. The new keyword creates the data somewhere in RAM and we simply store a pointer there. The address the pointer stores is copied over to `MySecondStruct`, but it still points to the same data. In fact, it would be counterproductive to remove this functionality since there are cases where you want exactly that. Additionally the Unreal Property System does not support non-UObject pointers, which is why `MyIntArray` is not marked with `UPROPERTY()`.

However, copying arrays of integers (e.g. `int32[10]` instead of `int32*`) means the data is stored directly inside the struct and as such "deep copied". However, if you store a pointer to a `UObject`, this object is NOT deep copied! Once again only the pointer is copied and the original `UObject` left unchanged. Which is good because otherwise you might manipulate the wrong instance thinking you only had one to begin with leaving the original `UObject` unaffected, thus resembling a very nerve-wrecking and very difficult to track down bug!

### Automatic Make/Break in BP

Marking the `USTRUCT` as `BlueprintType` and adding `EditAnywhere, BlueprintReadWrite, Category = "Your Category"` to `USTRUCT` properties causes UE4 to automatically create Make and Break Blueprint functions, allowing to construct or extract data from the custom `USTRUCT`.

Special thanks to Community member **Iniside** for pointing this out. :)

```cpp
USTRUCT(BlueprintType)
struct FFlowerStruct
{
    GENERATED_BODY()

    UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Flower Struct")
    int32 NumPetals;

    UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Flower Struct")
    FLinearColor Color;

    UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Flower Struct")
    FVector Scale3D;
};
```

[image (todo)](https://app.gitbook.com/s/-M3mx7Lszp8LdwKKD7yR-3772691856/wiki-archives/macros-and-data-types/CustomUStructMakeBreak.jpg)

### Replication

Remember that only `UPROPERTY(`) variables of `USTRUCTS()` are considered for replication!

So if your `USTRUCT` is not replicating properly, the first thing you should check is that every member is at least `UPROPERTY()`! The struct does not have be a `BlueprintType`, it just needs `UPROPERTY()` above all properties that you want replicated.

### Other notes

In case you are looking for `GENERATED_USTRUCT_BODY`, in 4.11+, `GENERATED_BODY()` should be used instead.

### Related Links

[UStruct data member memory management](broken://pages/-M3oGdp6OytFDxuiNd7O)

### Thank You Epic for USTRUCTS()

I love `USTRUCTS()`, thank you Epic!

## Authors

Original author: Rama <3\
Captured from the epic wiki via the Wayback Machine. Reformatted by Maldonacho


# Enums For Both C++ and BP

This wiki article was written by Rama.

> This article is still in the process of being cleaned up, but it has been captured for preservation.

## Overview

Dear Community,

Here's how you can create your own Enums that can be used with C++ and BP graphs!

Enums basically give you ability to define a series of related types with long human-readible names, using a low-cost data type.

These could be AI states, object types, ammo types, weapon types, tree types, or anything really :)

![Enumgraph.jpg](https://d3ar1piqh1oeli.cloudfront.net/e/e3/Enumgraph.jpg/800px-Enumgraph.jpg)

### BP Graphs: Switch on Enum

For BP Graphs, one of the most wonderful things about ENUMS is the ability to use Switch on Enum() instead of having to do a series of branches and testing one value many times

### C++ .h File

You need to add the UENUM definition above your class and then actually create a member variable in your class that you want to have be an instance of this enum.

If you want an enum to be used in many different classes (instances of this enum in many classes) you can define the enum in some class that holds all your other important definitions like USTRUCTS().

```cpp
UENUM(BlueprintType)
enum class EVictory : uint8 {
    VE_Dance       UMETA(DisplayName="Dance"),
    VE_Rain        UMETA(DisplayName="Rain"),
    VE_Song        UMETA(DisplayName="Song"),
};
```

### Testing the Value in the C++

```cpp
UCLASS()
class YourClass : public YourSuperClass {
    GENERATED_BODY()

public:
    UPROPERTY(EditAnywhere, BlueprintReadWrite)
    EVictory VictoryEnum;

};
```

```cpp
if (EVictory == EVictory::VE_Dance) {
    EVictory = EVictory::VE_Song;
} else {
    EVictory = EVictory::VE_Rain;
};
```

### Get Name of Enum as String

```cpp
FString GetVictoryEnumAsString(EVictory::Type EnumValue) {
const UEnum* EnumPtr = FindObject<UEnum>(ANY_PACKAGE, TEXT("EVictoryEnum"), true);
    if (!EnumPtr) return FString("Invalid");
        return EnumPtr->GetNameByValue((int64)EnumValue); // for EnumValue == VE_Dance returns "VE_Dance"
    }
}
```

#### Templatized Version

```cpp
// Example usage GetEnumValueAsString<EVictoryEnum>("EVictoryEnum", VictoryEnum))); 

template<typename TEnum>
static FORCEINLINE FString GetEnumValueAsString(const FString& Name, TEnum Value) {
    const UEnum* enumPtr = FindObject<UEnum>(ANY_PACKAGE, *Name, true);
    if (!enumPtr) return FString("Invalid");
    return enumPtr->GetNameByValue((int64)Value).ToString();
} 
```

&#x20;{ return FString("Invalid"); }

```
   return enumPtr->GetNameByValue((int64)Value).ToString();
```

}

// Example usage GetEnumValueAsString\<EVictoryEnum>("EVictoryEnum", VictoryEnum))); \</syntaxhighlight>

Also, if you want to avoid retyping the enum class name as a string on every call to GetEnumValueAsString, you can also define a c++ macro in the .h file where the function is defined.

For example, if you have defined GetEnumValueAsString in a class UTextUtil in TextUtil.h, you would have this macro

\<syntaxhighlight lang="cpp">

1. define EnumToString(EnumClassName, ValueOfEnum) UTextUtil::GetEnumValueAsString\<EnumClassName>(FString(TEXT(#EnumClassName)), (ValueOfEnum))

\</syntaxhighlight>

This way in any other file where you want a FString from an enum value, you would do:

```cpp
FString EnumString = EnumToString(EVictoryEnum, EVictoryEnum::VE_Dance);
```

### GetEnumFromString

If you want to retrieve an Enum value after storing the Enum as a string, here is how!&#x20;

```cpp
template <typename EnumType>
static FORCEINLINE EnumType GetEnumValueFromString(const FString& EnumName, const FString& String) {
  UEnum* Enum = FindObject<UEnum>(ANY_PACKAGE, *EnumName, true);
  if(!Enum) { 
    return EnumType(0);
  }		
  return (EnumType)Enum->FindEnumIndex(FName(*String));
}

//Sample Usage FString ParseLine = GetEnumValueAsString<EChallenge>("EChallenge", VictoryEnumValue))); //To String EChallenge Challenge = GetEnumValueFromString<EChallenge>("EChallenge", ParseLine); //Back From String!
```

### Summary

Now you know how to make enums that are project specific, that can be used in both C++ and Blueprints!

Enjoy!

Rama


# Delegates in UE4, Raw C++, and BP Exposed

This wiki article was written by Rama.

## Overview

In this wiki I share with you the core code that you need to implement for a variety of delegates in UE4!

A delegate is basically an event that you can define and call and respond to.

Every time the event is fired off, anyone who is listening for this event will receive it and be able to take appropriate action.

In the case of **multicast** delegates, any number of entities within your code base can respond to the same event and receive the inputs and use them.

In the case of **dynamic** delegates, the delegate can be saved/loaded within a Blueprint graph (they're called Events/Event Dispatcher in BP).

For my example I will be using exclusively DYNAMIC\_MULTICAST which is the type that is most useful in Blueprints :)

### Steps

**Signature**

You create the signature of the delegate, which declares what inputs any receiving functions should specify.

```cpp
//RamaMeleeWeapon class .h

DECLARE_DYNAMIC_MULTICAST_DELEGATE_SixParams( FRamaMeleeHitSignature, class AActor*, HitActor, class UPrimitiveComponent*, HitComponent, const FVector&, ImpactPoint, const FVector&, ImpactNormal, FName, HitBoneName, const struct FHitResult&, HitResult );
```

Notice the macro declares that I will be adding 6 parameters, there are similar macros for other quantities of parameters :)

```cpp
 DECLARE_DYNAMIC_MULTICAST_DELEGATE_SixParams
```

**Calling the Delegate**

You call the delegate within the class structure where it was defined, making sure to only execute it if it is currently bound, meaning at least 1 entity is listening for this delegate / event.

**.h**

```cpp
//.h
//RamaMeleeWeapon class .h

//This should be in the class which calls the delegate, and where the signature was defined
//This is an instance of the signature that was defined above!
FRamaMeleeHitSignature RamaMeleeWeapon_OnHit;
```

**.cpp**

```cpp
//.cpp
//Only the code that is supposed to initiate the event calls Broadcast()
if(RamaMeleeWeapon_OnHit.IsBound()) //<~~~~
{
	RamaMeleeWeapon_OnHit.Broadcast(Hit.GetActor(), Hit.GetComponent(), Hit.ImpactPoint, Hit.ImpactNormal, Hit.BoneName, Hit);
}
```

Comment from [Darkgaze](file:///index.php?title=User:Darkgaze\&action=edit\&redlink=1): As the official [Multicast docs](https://docs.unrealengine.com/latest/INT/Programming/UnrealArchitecture/Delegates/Multicast/index.html) say:

(...)It is always safe to call Broadcast() on a multi-cast delegate, even if nothing is bound. The only time you need to be careful is if you are using a delegate to initialize output variables, which is generally very bad to do.(...)

So calling InBound() is not necessary. Only in Single-cast delegates.

**Responding to the Delegate**

Anywhere you want, you can declare functions which receive the parameters by type and name specified in the delegate signature.

```cpp
//Any class can add a function that uses the delegate signature and responds to the Broadcast() event 
UFUNCTION()
void RespondToMeleeDamageTaken(AActor* HitActor, UPrimitiveComponent* HitComponent, const FVector& ImpactPoint, const FVector& ImpactNormal, FName HitBoneName, const FHitResult& HitResult)
```

See below to learn how to bind the delegate instance to this function or any number of functions that are present in class instances anywhere in your code base!

### UFUNCTION()  !

Please note that functions that are responding to delegate broadcasts should be UFUNCTION()!

If your delegate Broadcast stalls the game for a bit and then doesnt work, it's because you did not make one of your receiving functions a UFUNCTION()

<3 Rama

### Binding To The Delegate

#### Dynamic Delegates

```cpp
RamaMeleeWeaponComp->RamaMeleeWeapon_OnHit.AddDynamic(this, &USomeClass::RespondToMeleeDamageTaken); //see above in wiki
```

#### Multicast Delegates

Binding to non-dynamic requires this syntax:

```cpp
RamaMeleeWeaponComp->RamaMeleeWeapon_OnHit.AddUObject(this, &USomeClass::RespondToMeleeDamageTaken); //see above in wiki
```

<https://docs.unrealengine.com/en-us/Programming/UnrealArchitecture/Delegates/Multicast>

#### Non Multicast

Binding a UObject to a non-dynamic, non-multicast delegate requires you to use the following syntax.

```cpp
//in some class cpp file

RamaMeleeWeaponComp->RamaMeleeWeapon_OnHit.BindUObject(this, &USomeClass::RespondToMeleeDamageTaken); //see above in wiki
```

You need to access the delegate where it is stored, in my case this is the RamaMeleeWeaponComponent

The idea is you are telling the delegate instance that it is getting a new binding, to this SomeClass insance, which is why you include the this pointer.

So this code appears where you want to add the binding to the event/delegate, but it must refer to the one signature instance present in the original class instance.

So basically this delegate binding is **an agreement between two instances**, where one instance is of the class that declares and implements the delegate, and the other instance is any ole' class that has declared the function signature to match the delegate signature.

There's nothing abstract here, everything is instances, so you must bind your object instance to the delegate signature instance that is part of the instance of the class that is going to fire off the broadcasting.

This is why I have a pointer to RamaMeleeWeaponComp->RamaMeleeWeapon\_OnHit, and I am **also** including the this pointer so that the signature knows about the calling object instance.

The reason it is a this pointer is because the code above is run in the object that wants to bind to the delegate, so this is a self-referencing pointer to the UObject we are binding to the delegate.

### Raw C++ Class Instances

Raw delegates are used with non UObject classes, like plugin modules.

```cpp
RamaMeleeWeaponComp->RamaMeleeWeapon_OnHit.BindRaw(this, &FSomeRawCPPClass::RespondToMeleeDamageTaken);
```

### Slate Class Instances

Slate delegates use this syntax:

```cpp
RamaMeleeWeaponComp->RamaMeleeWeapon_OnHit.CreateSP(this, &SSomeSlateClass::RespondToMeleeDamageTaken);
```

### Binding is Per-Instance

Please note that when you bind to the delegate this is a per-instance process! That is why you need to include the this pointer, because whichever instance you are calling the code in, it is that particular instance whose function will get called when the delegate is broadcasted.

This means you can choose to have only certain instances of a uobject respond to a delegate, or choose to bind or unbind at any time!

### BP-Friendly Delegates

A BP friendly delegate requires this additional .h code to expose the delegate to Blueprints.

```cpp
//RamaMeleeWeapon.h

UPROPERTY(BlueprintAssignable, Category="Rama Melee Weapon")
FRamaMeleeHitSignature RamaMeleeWeapon_OnHit;
```

BP-friendly Delegates should be DYNAMIC\_MULTICAST so they can be serialized (saved/loaded) with the BP graph.

### Level Blueprint Friendly Delegates

When you've made BP-friendly delegates on objects that you can place in the level, you can simply right click on the object instance in your level -> Add Event and see your new delegate! So nice!

This is an additional benefit of using DYNAMIC\_MULTICAST delegates! Multi-cast implies binding multiple of various object instances to the delegate and then firing off the event to everyone from a single .Broadcast, which can include your Level Blueprint as a recipient/listener!

### Video Example

Here is a video on how a C++ delegate created in an actor component in C++ looks and is called in Blueprints!

The code in this wiki and this video are from my [Melee Weapon Plugin](http://ue4code.com/melee_weapon_system_plugin_per_bone_collision_accuracy)

<http://www.youtube.com/watch?v=aufEB4TCf30&t=5m24s>

### Further Reading

Epic Documentation: <https://docs.unrealengine.com/latest/INT/Programming/UnrealArchitecture/Delegates/>

### DYNAMIC\_MULTICAST And Other Types

There are other delegate types besides DYNAMIC\_MULTICAST that are not quite as versatile when it comes to Blueprints.

Check out the source code of Delegate.h:`Runtime/Core/Public/Delegates/Delegate.h`

For a detailed explanation!

Sample from this file:

```
**
 *  C++ DELEGATES
 *  -----------------------------------------------------------------------------------------------
 *
 *	This system allows you to call member functions on C++ objects in a generic, yet type-safe way.
 *  Using delegates, you can dynamically bind to a member function of an arbitrary object,
 *	then call functions on the object, even if the caller doesn't know the object's type.
 *
 *	The system predefines various combinations of generic function signatures with which you can
 *	declare a delegate type from, filling in the type names for return value and parameters with
 *	whichever types you need.
 *
 *	Both single-cast and multi-cast delegates are supported, as well as "dynamic" delegates which
 *	can be safely serialized to disk.  Additionally, delegates may define "payload" data which
 *	will stored and passed directly to bound functions.
```

### Conclusion

Enjoy using delegates in UE4 so that any part of your code base can respond to an event triggered by one section of your code!

Also enjoy exposing delegates via C++ for the rest of your team to use in Blueprints!

Enjoooy!

♥

Rama


# Interfaces in C++

This wiki article was originally written by Rama and received contributions from HuntaKiller, DarkGaze, and Ruhrpottpatiot.

## Overview

Here's a tutorial on using **UE4 C++ Interfaces in 4.11+**

Interfaces allow different objects to share common functions, but allow objects to handle that function differently if it needs to. Any classes that use an interface must implement the functions that are associated with that interface.

This gives you a lot of power over your game actors, allowing you to trigger events both in C++ and in blueprints that your game actors can handle differently.

For example, the interface implemented in this tutorial enables you to have an interface like TimeBasedBehaviour, which has a function ReactToHighNoon, and have a bunch of actors respond to this event differently, each with their own behaviour.

Flower actors that implement this interface could override the ReactToHighNoon method to open blossoms completely Frog actors implementing it could override ReactToHighNoon to hide under rocks, for example

You can then have an event, SunReachedHighNoon that is triggered anywhere (such as the level blueprint, in an actor, or a static blueprint library) which can take any actor, check if it implements the interface, and if it does it can call any of the functions of that interface and the actor will act according to how that specific actor has the behaviours defined.

This means you can trigger events anywhere and as long as you have a pointer to your actor, you can ask it to do specific things without needing to know its types because you can **easily determine whether any given actor has an interface or not by casting an actor to that interface**. If the cast succeeds then the actor does implement the given interface, and you can call functions using that interface.

We will implement two interface functions: one which forces you to implement default C++ behaviour on any class which uses the interface, a **BlueprintNativeEvent** called ReactToHighNoon(), and one **BlueprintImplementableEvent** which does not force you to define default C++ behaviour, called ReactToMidnight().

### Creating The Interface

The following is an example implementation of a ReactsToTimeOfDay interface.

When following this tutorial and creating your interface, you'd replace ReactToHighNoon() with your function you want to force default behaviour, and ReactToMidnight() with your function that has no default behaviour.

(If you wish the function to be treated as an event, then it must return void. If you wish the function to be able to be overridden in the BP editor, then it must have a non-void return type. Replace the return type of the function with a string or void if you want to perform a simplistic test. The reasoning is discussed further below in the Critical To Note section)

#### ReactsToTimeOfDay.h

```cpp
#pragma once

#include "ReactsToTimeOfDay.generated.h"

/**
 * Must have BlueprintType as a specifier to have this interface exposed to blueprints.
 * With this line you can easily add this interface to any blueprint class.
 */
UINTERFACE(BlueprintType)
class MYPROJECT_API UReactsToTimeOfDay : public UInterface {
  GENERATED_UINTERFACE_BODY()
};

class MYPROJECT_API IReactsToTimeOfDay {
  GENERATED_IINTERFACE_BODY()

public:

  // classes using this interface must implement ReactToHighNoon
  UFUNCTION(BlueprintNativeEvent, BlueprintCallable, Category = "MyCategory")
  bool ReactToHighNoon();

  //classes using this interface may implement ReactToMidnight
  UFUNCTION(BlueprintImplementableEvent, BlueprintCallable, Category = "MyCategory")
  bool ReactToMidnight();

};
```

> **Note checked for 4.18+:** `GENERATED_UINTERFACE_BODY()` and `GENERATED_IINTERFACE_BODY()`, can be now changed to `GENERATED_BODY()`, which is an updated version of those two that works for structs, etc, but errors could be a little confusing if you get compile errors since there's no way to differentiate. You could create an automatic interface to see how it looks now using Create C++ Class context menu on the content editor and choosing Interface type.

#### ReactsToTimeOfDay.cpp

```cpp
#include "MyProject.h"
#include "ReactsToTimeOfDay.h"

UReactsToTimeOfDay::UReactsToTimeOfDay(const class FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) {
  // add your code here
}
```

### Using An Interface With C++ Classes

You have to use **multiple inheritance**, and inherit from the IReactsToTimeOfDay class we created.

The first inherited class will be the base class of your actor, anything you want, a ASkeletalMeshActor is used here as an example.

#### Flower.h

```cpp
#include "ReactsToTimeOfDay.h"
#include "ASkeletalMeshActor.generated.h"

// ...other includes may appear here depending on your class

UCLASS()
class AFlower : public ASkeletalMeshActor, public IReactsToTimeOfDay {
  GENERATED_BODY()

public:

  /* ... other AFlower properties and functions declared ... */

  UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category = "MyCategory")
  bool ReactToHighNoon(); virtual bool ReactToHighNoon_Implementation() override;

};
```

`virtual bool ReactToHighNoon_Implementation() override;`

This line tells your class that it has a function of this name and signature to inherit from the interface, which is how calls to the interface functions are able to interact with this class.

`UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category = "MyCategory") bool ReactToHighNoon();`&#x20;

This tells your class that you can both call and override this function in blueprints. You need this part as well if you want to be able to override C++ functionality within BP, as BlueprintNativeEvents are intended to be used.

Notice that `ReactToMidnight()`, the BlueprintImplementableEvent, is not defined here. A BlueprintImplementableEvent is declared (its existance) in our interface, but defined (its behaviour) in blueprints only.

#### Flower.cpp

```cpp
// other flower.cpp code

bool AFlower::ReactToHighNoon_Implementation() {
 // Default behaviour for how flower would react at noon //OpenPetals(); //AcceptBugs(); //...
 return true;
} 
```

Any number of classes and subclasses can implement this interface using this format

#### Frog.h

```cpp
#include "ReactsToTimeOfDay.h"
#include "AFrog.generated.h"

UCLASS()
class AFrog : public ACharacter, public IReactsToTimeOfDay {
  GENERATED_BODY()
  
  /* ... other AFrog properties and functions declared ... */

  UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category = "MyCategory")
  bool ReactToHighNoon(); virtual bool ReactToHighNoon_Implementation() override;
  
};
```

#### Frog.cpp

```cpp
// other Frog code

bool AFrog::ReactToHighNoon_Implementation() {
  // Default behaviour for how a frog would react at noon //GoSwim(); //...
  return true;
}
```

#### Determining If a Given Actor Has The Interface

To determine if an actor implements an interface in C++, simply cast your class to the interface, if it returns NULL then the object is not using it. If it is successful, you can use that pointer cast to the interface to call your function, which will execute from the proper class.

```cpp
// Example: somewhere else in code we are trying to see if our object reacts to time of day
// Some pointer is defined to any class inheriting from UObject UObject* pointerToAnyUObject;

IReactsToTimeOfDay* TheInterface = Cast<IReactsToTimeOfDay>(pointerToAnyUObject);
if (TheInterface) {
  // Don't call your functions directly, use the 'Execute_' prefix //the Execute_ReactToHighNoon
  // and Execute_ReactToMidnight are generated on compile //you may need to compile before these
  // functions will appear TheInterface->Execute_ReactToHighNoon (pointerToAnyUObject);
  TheInterface->Execute_ReactToMidnight (pointerToAnyUObject);
}

//end of code segment
```

&#x20;**Critical To Note**

* &#x20;Whenever calling your interface functions in C++, never call the direct functions, always use the one with the Execute\_ prefix
* &#x20;Although it might seem, that you function must return a value to be properly implemented, this is not true. If your interface doesn't return a value UE4 treats it as an event. At first glance this might seem as an error, but this is not the case. You just have to create the implementation details in the event graph instead of overriding. You still can call the function normally via function, or interface call. --Ruhrpottpatiot
* &#x20;To determine if an actor implements an interface in both C++ and Blueprints use

```cpp
if (pointerToAnyUObject->GetClass()->ImplementsInterface(UReactsToTimeOfDay::StaticClass())) {
    IReactsToTimeOfDay::Execute_ReactToHighNoon(pointerToAnyUObject);
}
```

#### The Magic Interfaces

```cpp
TheInterface->Execute_ReactToHighNoon();
```

From the above code you can see that the function is being called off of the interface, you never even need to know what type of object you're dealing with, just whether it supports the interface you need.

It produces different results depending on the actual class it is, calling the overridden function. This is called polymorphism.

### Overriding Behaviour In Blueprints

Once this is all implemented, the classes that you have set up with the interface in C++ will have its interface functions appear with the blueprint's variables and other functions.

[![InterfaceBP1.png](https://web.archive.org/web/20181002150134im_/https://d26ilriwvtzlb.cloudfront.net/7/7b/InterfaceBP1.png)](https://web.archive.org/web/20181002150134/https://wiki.unrealengine.com/index.php?title=File:InterfaceBP1.png)

[![InterfaceBP2.png](https://web.archive.org/web/20181002150134im_/https://d26ilriwvtzlb.cloudfront.net/6/6a/InterfaceBP2.png)](https://web.archive.org/web/20181002150134/https://wiki.unrealengine.com/index.php?title=File:InterfaceBP2.png)

\
&#x20;Again, your function **must** have a return value for it to appear in this list, otherwise it is considered an event and cannot be overridden as a function. You can however use the event from the interface in blueprint's event graph and override it that way.

### Summary

You can trigger global events that only certain actors will respond to each actor can respond to an event in their own unique way.&#x20;

While it's a little bit more complicated of a setup it helps keeping the code very simple and is much more performance friendly than casting to multiple different types of classes!


# Iterators

Object & Actor Iterators, Optional Class Scope For Faster Search

### Overview

Dear Community,

In the UE4 engine two of the most powerful tools I use constantly are the Object and the Actor Iterators.

You can use these functions to search for all Run-Time instances of actors and objects, or only specific classes!

**The advantage of using the UE4 iterators is that they are always accurate!**

You dont have to maintain dynamic arrays of actors, and then remember to remove actors when they are destroyed!

The Actor and Object Iterators always give you the real and accurate list of all actors / objects currently still active in your game world

Yay!

#### Include

**#include "EngineUtils.h"**

**Controller Class**

You dont have to use these functions in the Controller Class,

I was just doing this for the sake of ClientMessage and easy testing on your part :)

### Object Iterator

```cpp
void AYourControllerClass::PrintAllObjectsNamesAndClasses()
{
    for ( TObjectIterator<UObject> Itr; Itr; ++Itr )
    {
        ClientMessage(Itr->GetName());
        ClientMessage(Itr->GetClass()->GetDesc());
    }
}
```

### Actor Iterator

```cpp
void AYourControllerClass::PrintAllActorsLocations()
{
    //EngineUtils.h
    for (TActorIterator<AActor> ActorItr(GetWorld()); ActorItr; ++ActorItr )
    {
        ClientMessage(ActorItr->GetName());
        ClientMessage(ActorItr->GetActorLocation().ToString());
    }
}
```

### Object Iterator & Actor Iterator Comparison

#### Disadvantage of Object Iterator

Unlike the Actor Iterator, the Object iterator is going to iterate over objects in the Pre-PIE world / the Editor World.

This can lead to unexpected results.

This is not an issue if you are running your game as an independent Game Instance / the editor is closed :)

#### Critical Advantage of Object Iterator

A critically important advantage of the Object Iterator is that it does not require a UWorld\* Context!

Notice how all the uses of Actor Iterator involve GetWorld()

```cpp
TActorIterator ActorItr<AStaticMeshActor>(GetWorld());
```

If you need to find an object in the game world from a static context, where you cannot obtain the UWorld via some other means,

then the Object Iterator is the way to get the proper context and access the entire living game world!

#### Object Iterator Can Search for AActors

Because AActor extends UObject, the Object Iterator can search for AActors!

But the AActor Iterator cannot search for instances of UObjects that do not extend AActor at some point.

So the Object Iterator can do a search for all UStaticMeshComponents, as well as all ACharacters!

```cpp
TObjectIterator<UStaticMeshComponent> Itr;
```

```cpp
TObjectIterator<ACharacter> Itr;
```

### Specifying Classes & Subclasses To Search For

Perhaps the most powerful feature of the Actor and Object Iterators is the ability to limit the scope of the search to a chosen base class and its subclasses!

This makes the iterator run faster and helps you gather only the data you really want from the game world!

#### Object Iterator, Specific Base Class

```cpp
void AYourControllerClass::PrintAllSkeletalMeshComponentsNames()
{
    for ( TObjectIterator<USkeletalMeshComponent> Itr; Itr; ++Itr )
    {
        ClientMessage(Itr->GetName());
    }
}
```

#### Actor Iterator, Specific Base Class

```cpp
void AYourControllerClass::PrintAllStaticMeshActorsLocations()
{
    //EngineUtils.h
    for (TActorIterator<AStaticMeshActor> ActorItr(GetWorld()); ActorItr; ++ActorItr)
    {
        ClientMessage(ActorItr->GetName());
        ClientMessage(ActorItr->GetActorLocation().ToString());
    }
}
```

### Using a World-Filter with ObjectIterator

ObjectIterator can and will return editor-instance / default object objects that simply should not be edited at runtime!

To filter out objects that you should not be editing at runtime, you can do a world check with an object that you know is part of the correct world (not the editor world)!

```cpp
UWorld* YourGameWorld = //set this somehow, from another UObject or pass it in as parameter

for(TObjectIterator<UYourObject> Itr; Itr; ++Itr)
{
   //World Check
   if(Itr->GetWorld() != YourGameWorld)
   {
      continue;
   }
   //now do stuff
}
```

#### In-Engine Example \~ Get All Widgets Of Class

The above is the code structure that I used for my Get All Widgets of Class node, pull request that Epic accepted that is now live in 4.7 !

**Github Link**

<https://github.com/EpicGames/UnrealEngine/pull/569>

I avoid getting the UMG widget default objects /editor objects by passing in the world using the Blueprint method of setting a WorldContextObject!

Enjoy!

## Authors

Original author: Rama <3

Ported from wiki by Firefly74940


# String Conversions: FString to FName, FString to Int32, Float to FString

Guide on String conversions (from/to) by Rama the legend

**Content**

* [Overview](/4.25/wiki-archives/macros-and-data-types/string-conversions#overview)
  * [Converting FString to FNames](/4.25/wiki-archives/macros-and-data-types/string-conversions#converting-fstring-to-fnames)
  * [std::string to FString](/4.25/wiki-archives/macros-and-data-types/string-conversions#std--string-to-fstring)
  * [FString to std::string](/4.25/wiki-archives/macros-and-data-types/string-conversions#fstring-to-std--string)
* [FCString Overview](/4.25/wiki-archives/macros-and-data-types/string-conversions#fcstring-overview)
  * [Converting FString to Numbers](/4.25/wiki-archives/macros-and-data-types/string-conversions#converting-fstring-to-numbers)
  * [FString to Integer](/4.25/wiki-archives/macros-and-data-types/string-conversions#fstring-to-integer)
  * [FString to Float](/4.25/wiki-archives/macros-and-data-types/string-conversions#fstring-to-float)
* [Float/Integer to FString](/4.25/wiki-archives/macros-and-data-types/string-conversions#float-integer-to-fstring)
* [UE4 Source Header References](/4.25/wiki-archives/macros-and-data-types/string-conversions#ue4-source-header-references)
* [Optimization Issues Concerning FNames](/4.25/wiki-archives/macros-and-data-types/string-conversions#optimization-issues-concerning-fnames)

## Overview

**Original Author: Rama**

Below are conversions for the following types: 1. FString to FName 2. std::string to FString 3. FString and FCString Overview 4. FString to Integer 5. FString to Float 6. Float/Integer to FString 7. UE4 C++ Source Header References 8. Optimization Issues Concerning FNames

All the header files I refer to in this tutorial are found in

```
your UE4 install directory  / Engine / Source
```

you will probably want to do a search for them from this point :)

### Converting FString to FNames

Say we have

```cpp
FString TheString = "UE4_C++_IS_Awesome";
```

To convert this to an FName you do:

```cpp
FName ConvertedFString = FName(*TheString);
```

### std::string to FString

```cpp
#include <string>
//....
std::string TestString = "Happy"; 
FString HappyString(TestString.c_str());
```

### FString to std::string

```cpp
#include <string>
//....
FString UE4Str = "Flowers";
std::string MyStdString(TCHAR_TO_UTF8(*UE4Str));
```

You will find this particularly useful in cases other than float and int32! C++ std::String::to\_string <http://en.cppreference.com/w/cpp/string/basic_string/to_string>

## FCString Overview

### Converting FString to Numbers

The *operator on FStrings returns their TCHAR* data which is what FCString functions use. If you cant find the function you want in FStrings (UnrealString.h) then you should check out the FCString functions (CString.h) I show how to convert from FString to FCString below: Say we have

```cpp
FString TheString = "123.021";
```

### FString to Integer

(note Atoi is unsafe; no way to indicate errors)

```cpp
int32 MyShinyNewInt = FCString::Atoi(*TheString);
```

### FString to Float

```cpp
float MyShinyNewFloat = FCString::Atof(*TheString);
```

Note that Atoi and Atof are static functions, so you use the syntax FCString::TheFunction to call it :)

## Float/Integer to FString

```cpp
FString NewString = FString::FromInt(YourInt);
FString VeryCleanString = FString::SanitizeFloat(YourFloat);
```

Static functions in the UnrealString.h :)

## UE4 Source Header References

```cpp
CString.h
UnrealString.h
NameTypes.h
```

See CString.h for more details and other functions like

```cpp
atoi64 (string to int64)
Atod    (string to double precision float)
```

For a great deal of helpful functions you will also want to look at UnrealString.h for direct manipulation of FStrings!

## Optimization Issues Concerning FNames

FNames are inherently fast, but you could be forcing a hashmap lookup if you are accessing them in the wrong way. Look at the following code:

```cpp
if (ActorHasTag(TEXT("MyFNameActor_Tag")))
```

This code will take the character string "MyFNameActor\_Tag" and then look it up in the FName hashmap. Whereas this code doesn't need to do a string conversion:

```cpp
static const FName NAME_MyFNameActor(TEXT("MyFNameActor_Tag"));
if (ActorHasTag(NAME_MyFNameActor))
```

In our testing with UE4 4.14, the second method is nearly 100 times faster than using the string lookup. So please, always use the static const FName method over the TEXT() method. For more info on FNames check out

```cpp
NameTypes.h
```

Enjoy!

## Authors

Original author: Rama <3\
Minor Authors: Kory\
Captured from the epic wiki via the Wayback Machine. Reformatted by DarioMazzanti


# Networking


# Standalone Dedicated Server

This guide shows you how to package and compile your game as a standalone dedicated server for both Windows and Linux.

## Standalone Dedicated Server

*This is currently only possible using an engine compiled from source. It is not possible through an engine installed via the Epic Launcher. This was deemed necessary due to the increase in size that would occur if the required files were included in the installed version of the engine.*

### Packaging the Content

The dedicated server needs packaged content. Go to File -> Package Project -> Packaging Settings. Here you have a few options:

* Use Pak File: Pack all the assets into one .pak file - disable if you want to have the regular content structure (e.g. for incremental uploads)
* Full Rebuild: You might want to disable this to lower packaging times

  Then go to File -> Package Project -> Package Windows/Linux and select an output directory. The engine will now package the content and compile the standalone client code - this may take some time in case of a full rebuild.

### Compiling the Server

#### Linux Compiler Toolchain

Linux compilation is currently only supported on Windows using a cross-compilation toolchain based on Clang. A precompiled toolchain from Epic is available here: <https://github.com/EpicGames/UnrealEngine/releases/tag/4.1.0-release>. After you unzipped the toolchain, make sure to add the environment variable LINUX\_ROOT and set it to the location of the toolchain (see README.md for details).

#### Compilation

The next step is to compile the server code using Visual Studio. First, you need to set up a special server target for UnrealBuildTool.

You can use the following template:

```cpp
// Copyright 1998-2014 Epic Games, Inc. All Rights Reserved.

using UnrealBuildTool;
using System.Collections.Generic;

public class GameServerTarget : TargetRules
{
    public GameServerTarget(TargetInfo Target)
    {
        Type = TargetType.Server;
    }

    //
    // TargetRules interface.
    //
    public override void SetupBinaries(
        TargetInfo Target,
        ref List<UEBuildBinaryConfiguration> OutBuildBinaryConfigurations,
        ref List<string> OutExtraModuleNames
        )
    {
        base.SetupBinaries(Target, ref OutBuildBinaryConfigurations, ref OutExtraModuleNames);
        OutExtraModuleNames.Add("Game");
    }

    public override bool GetSupportedPlatforms(ref List<UnrealTargetPlatform> OutPlatforms)
    {
        // It is valid for only server platforms
        return UnrealBuildTool.UnrealBuildTool.GetAllServerPlatforms(ref OutPlatforms, false);
    }

    public override List<UnrealTargetPlatform> GUBP_GetPlatforms_MonolithicOnly(UnrealTargetPlatform HostPlatform)
    {
        if (HostPlatform == UnrealTargetPlatform.Mac)
        {
            return new List<UnrealTargetPlatform>();
        }
        return new List<UnrealTargetPlatform> { HostPlatform, UnrealTargetPlatform.Win32, UnrealTargetPlatform.Linux };
    }

    public override List<UnrealTargetConfiguration> GUBP_GetConfigs_MonolithicOnly(UnrealTargetPlatform HostPlatform, UnrealTargetPlatform Platform)
    {
        return new List<UnrealTargetConfiguration> { UnrealTargetConfiguration.Development };
    }
}
```

Just replace all instances of "Game" with the name of your game project.

Its possible that there are no functions to override by the overrides so it will not build. Throw these out aswell if there are problems.

Save it as `<Game>Server.Target.cs` next to the other target files and regenerate the project files.

Open Visual Studio, set the configuration to \*Server and select the platform target accordingly.

Now it's time to build your game project. Using the above UBT target, the executable will end up in `<game>/Binaries/<platform>/<Game>Server`. Move the executable over to `<cooked>/<platform>/<game>/binaries/<platform>`.

### Platform Specifics

#### Windows

Simply execute `<Game>Server.exe`. If you want a log window, start with `-log`.

#### Linux

The server will listen for UDP packets on port 7777 by default, so make sure to open this port in your firewall.

With some Unreal Engine releases (4.2 and below) you can run into this message if you don't pass -pak:

```
Could not adjust number of file handles, consider changing "nofile" in /etc/security/limits.conf and relogin.
```

The solution is to pass -pak on the command line when starting the server.

## Authors

Original author: **Epic Games**\
Captured from the epic wiki via the Wayback Machine. Reformatted by Maldonacho


# How To Use Sessions In C++

## Features for the future

* &#x20;Example of network error handling. Like getting disconnected due to a server shutdown.
* &#x20;Example of getting information into UMG. Like the Serverlist.
* &#x20;Example of extending the GameSession class. Adding more information to your GameSession.
* &#x20;Example of extending several other classes that you can make your Session System unique and you will directly understand the ShooterGame after learning all of this.

## What is this Tutorial about?

In this Tutorial, I'm going to show you a very basic Code to Create, Find, Join and Destroy Session in C++. So basically we are going to create the Blueprint Session Nodes.

## Getting Started

### Prepare your Project to use Sessions and OnlineSubsystems

So first of all, we need to get your Project ready to use all of this. I recommend you to start with an empty project, so you can first get an idea how this works, before trying to implement this into your already started project!

#### Changing the "DefaultEngine.ini"

You can find the "DefaultEngine.ini" file in the Config folder in your top most project folder. You will want to add the following line to it:

```
[OnlineSubsystem]
DefaultPlatformService=Null
```

#### Changing the "YourProjectName.Build.cs"

You can find this file in your Project when you opened it with Visual Studio. You need to add "OnlineSubsystem", "OnlineSubsystemUtils" (for later usage) and the OnlineSubsystem NULL. It should look similar to this:

```csharp
using UnrealBuildTool;

public class NetworkSessionTest : ModuleRules
{
    public NetworkSessionTest(TargetInfo Target)
    {
         PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore", "OnlineSubsystem", "OnlineSubsystemUtils" });

         DynamicallyLoadedModuleNames.Add("OnlineSubsystemNull");
    }
}
```

#### Changing the "YourProjectName.h"

This file can also be found in the Project when you open it with Visual Studio. You want to change

```cpp
#include "EngineMinimal.h" 
```

to

```cpp
#include "Engine.h".
```

As well as add these two #includes under the "Engine.h" one.

```cpp
#include "UnrealNetwork.h"
#include "Online.h"
```

So your file looks something like this:

```cpp
#ifndef __NETWORKSESSIONTEST_H__
#define __NETWORKSESSIONTEST_H__

#include "Engine.h"
#include "UnrealNetwork.h"
#include "Online.h"
#endif
```

And that's it for setting up the Project!

### My TestProject Setup

So, i want to let you know how my test project is setup and what i am using. I create a new fresh C++ Thirst Person Project and added **ONE** Class.

I made a child class of "UGameInstance" and called it "UNWGameInstance". (NW = Network). This is what i am referring to from now on and what you will read when seeing my function. Because every function for Creating, Finding,.. Sessions will be placed here.

## Code to Create, Find, Join and Destroy Sessions

We are using a lot of Unreal Engine 4's functions here. All these functions are placed in an "SessionInterface" that is designed to handle sessions for different OnlineSubsystems. So although we are using "NULL" here, this should also work with Steam and other Subsystems. At least for the basics that all Subsystems share.

These functions all call a so called "delegate" once they are finished doing what they should do. All Session actions can take some time, so these functions are important. We will create 1-2 delegates, handles and functions for every one of these 4 Sessions operations. They will give us information like if the action was successful or not.

#### Terms you will read a lot about

| Word/Term         | Explanation                                                                                                                                                                                                                                                                                                                                             |
| ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| OnlineSubsystem   | OnlineSubsystems are for example "Steam". But you can also use "NULL", which is simply the basic UE4 Subsystem. They all use so called "Wrapper"-Functions. They give us Friend Lists, Unique IDs or Master Server that allow us to find Servers over the Internet and not only on LAN!                                                                 |
| Wrapper Functions | Wrapper Functions are something really cool that makes it easy for us to setup the Sessions for all different OnlineSubsystems. While we only need to call "CreateSession", this wrapper function will do the necessary steps to Create a Session in the active Subsystem. So we can create our logic without thinking about Steam or other Subsystems. |
| Session           | A Session is not the Map or the Server itself. A Session is an invisible thing that a Server can Create and a Client can join. They will still need to join the specific Map after joining the Session. A Session is more like an entry in a Database that helps you keeping track of all running Servers.                                              |
| Session Interface | That is nearly the same as the Session explained above. We will use the Interface instead of the Session itself, because it uses the Wrapper functions we need. We can always get this Internet if we have a valid OnlineSubsystem!                                                                                                                     |

### Creating a Session

Yes, let's start with creating a simple Session. I will always post the things we put into the Header file first and after that the logic will fill in with the .cpp File! This will all be placed in the UGameInstance Child class i have created. We don't need other classes.

**So what do we need?**

**Creating a Session | Header File**

First we need a function we can use to gather all the settings we want to use for our Session. Let's call this function "HostSession".

```cpp
In our UNWGameInstance.h:

/**
*	Function to host a game!
*
*	@Param		UserID			User that started the request
*	@Param		SessionName		Name of the Session
*	@Param		bIsLAN			Is this is LAN Game?
*	@Param		bIsPresence		"Is the Session to create a presence Session"
*	@Param		MaxNumPlayers	        Number of Maximum allowed players on this "Session" (Server)
*/
bool HostSession(TSharedPtr<const FUniqueNetId> UserId, FName SessionName, bool bIsLAN, bool bIsPresence, int32 MaxNumPlayers);
```

The comments explain a lot already, so i will step back from explaining the parameters in the function declarations.

Now we also need the Delegates i talked about earlier. They are used by the "CreateSession" function of the SessionInterface to tell use when the process is done.

```cpp
// In our UNWGameInstance.h:

/* Delegate called when session created */
FOnCreateSessionCompleteDelegate OnCreateSessionCompleteDelegate;
/* Delegate called when session started */
FOnStartSessionCompleteDelegate OnStartSessionCompleteDelegate;

/** Handles to registered delegates for creating/starting a session */
FDelegateHandle OnCreateSessionCompleteDelegateHandle;
FDelegateHandle OnStartSessionCompleteDelegateHandle;
```

So we have a Delegate and a Handle for Creating and Starting a Session. Now we also need a variable we use for the Settings that our Session will have (like LAN or Number of allowed Players):

```cpp
// In our UNWGameInstance.h:

TSharedPtr<class FOnlineSessionSettings> SessionSettings;
```

And we will also add a Constructor to our GameInstance class, which is called when the Object is created. We need this to bind the functions to the delegates!

```cpp
// In our UNWGameInstance.h

UNWGameInstance(const FObjectInitializer& ObjectInitializer);
```

And finally, we need a function that we bind to the Delegate, so we can perform some actions once we know that the Creation process is complete:

```cpp
// In our UNWGameInstance.h:

/**
*	Function fired when a session create request has completed
*
*	@param SessionName the name of the session this callback is for
*	@param bWasSuccessful true if the async action completed without error, false if there was an error
*/
virtual void OnCreateSessionComplete(FName SessionName, bool bWasSuccessful);

/**
*	Function fired when a session start request has completed
*
*	@param SessionName the name of the session this callback is for
*	@param bWasSuccessful true if the async action completed without error, false if there was an error
*/
void OnStartOnlineGameComplete(FName SessionName, bool bWasSuccessful);
```

Again, the Comments explain the parameters. These function will have different values for their parameters depending on if the process was successful or not!

**Creating a Session | CPP file**

Now we fill these functions with logic.

First of all, we will bind the functions to the delegates in our Constructor:

```cpp
// In our UNWGameIntance.cpp:

UNWGameInstance::UNWGameInstance(const FObjectInitializer& ObjectInitializer)
	: Super(ObjectInitializer)
{
	/** Bind function for CREATING a Session */
	OnCreateSessionCompleteDelegate = FOnCreateSessionCompleteDelegate::CreateUObject(this, &UNWGameInstance::OnCreateSessionComplete);
	OnStartSessionCompleteDelegate = FOnStartSessionCompleteDelegate::CreateUObject(this, &UNWGameInstance::OnStartOnlineGameComplete);
}
```

All upcoming bindings for the other operations will be placed in this Constructor, under these two binds.

Now let's have a look at the "HostSession" function we created:

```cpp
// In our UNWGameIntance.cpp:

bool UNWGameInstance::HostSession(TSharedPtr<const FUniqueNetId> UserId, FName SessionName, bool bIsLAN, bool bIsPresence, int32 MaxNumPlayers)
{
	// Get the Online Subsystem to work with
	IOnlineSubsystem* const OnlineSub = IOnlineSubsystem::Get();

	if (OnlineSub)
	{
		// Get the Session Interface, so we can call the "CreateSession" function on it
		IOnlineSessionPtr Sessions = OnlineSub->GetSessionInterface();

		if (Sessions.IsValid() && UserId.IsValid())
		{
			/* 
				Fill in all the Session Settings that we want to use.
				
				There are more with SessionSettings.Set(...);
				For example the Map or the GameMode/Type.
			*/
			SessionSettings = MakeShareable(new FOnlineSessionSettings());

			SessionSettings->bIsLANMatch = bIsLAN;
			SessionSettings->bUsesPresence = bIsPresence;
			SessionSettings->NumPublicConnections = MaxNumPlayers;
			SessionSettings->NumPrivateConnections = 0;
			SessionSettings->bAllowInvites = true;
			SessionSettings->bAllowJoinInProgress = true;
			SessionSettings->bShouldAdvertise = true;
			SessionSettings->bAllowJoinViaPresence = true;
			SessionSettings->bAllowJoinViaPresenceFriendsOnly = false;

			SessionSettings->Set(SETTING_MAPNAME, FString("NewMap"), EOnlineDataAdvertisementType::ViaOnlineService);

			// Set the delegate to the Handle of the SessionInterface
			OnCreateSessionCompleteDelegateHandle = Sessions->AddOnCreateSessionCompleteDelegate_Handle(OnCreateSessionCompleteDelegate);

			// Our delegate should get called when this is complete (doesn't need to be successful!)
			return Sessions->CreateSession(*UserId, SessionName, *SessionSettings);
		}
	}
	else
	{
		GEngine->AddOnScreenDebugMessage(-1, 10.f, FColor::Red, TEXT("No OnlineSubsytem found!"));
	}

	return false;
}
```

Since i commented everything and this is VERY similar to the upcoming functions, i will only explain this once:

The first thing we do is getting our OnlineSubsystem, because we need the SessionInterface from it. Once we made sure that it is valid, we get the SessionInterface and make sure this and the UsedId are valid.

Then we set a lot of different SessionSettings, like Number of Players etc. After we did this, we going to setting the delegate of the "CreateSessionsComplete" handle to the one we create and that we bound a functions to. So we make sure, that this is the one getting used and called once the "CreateSession" process is finished. We will do this for every Session operation from now on, so i won't explain this again.

Once we did this, we are going to call the "CreateSession" function of the Session Interface and we are done. Now it could take some seconds until it is finished and the Engine calls our Delegate Functions, which we will fill with logic now:

```cpp
// In our UNWGameIntance.cpp:

void UNWGameInstance::OnCreateSessionComplete(FName SessionName, bool bWasSuccessful)
{
	GEngine->AddOnScreenDebugMessage(-1, 10.f, FColor::Red, FString::Printf(TEXT("OnCreateSessionComplete %s, %d"), *SessionName.ToString(), bWasSuccessful));

	// Get the OnlineSubsystem so we can get the Session Interface
	IOnlineSubsystem* OnlineSub = IOnlineSubsystem::Get();
	if (OnlineSub)
	{
		// Get the Session Interface to call the StartSession function
		IOnlineSessionPtr Sessions = OnlineSub->GetSessionInterface();

		if (Sessions.IsValid())
		{
			// Clear the SessionComplete delegate handle, since we finished this call
			Sessions->ClearOnCreateSessionCompleteDelegate_Handle(OnCreateSessionCompleteDelegateHandle);
			if (bWasSuccessful)
			{
				// Set the StartSession delegate handle
				OnStartSessionCompleteDelegateHandle = Sessions->AddOnStartSessionCompleteDelegate_Handle(OnStartSessionCompleteDelegate);

				// Our StartSessionComplete delegate should get called after this
				Sessions->StartSession(SessionName);
			}
		}
		
	}
}
```

Here again, we will get the OnlineSubsystem and the SessionInterface. This will, again, repeat a lot of times now. Once we made sure that the SessionInterface is valid, we clear the Delegate from the handle, because the call is finished and we want to bind it next time we call "CreateSession". That's why we need to clear it.

After that, we can check if the process was "Successful". If yes, we set the Delegate of the "StartSessionComplete" handle and call the "StartSession" function with the "SessionName" we got. This is already the new Session we created!

This will also take an amount of time but once it is finished, the Engine calls the second Delegate function we created:

```cpp
// In our UNWGameIntance.cpp:

void UNWGameInstance::OnStartOnlineGameComplete(FName SessionName, bool bWasSuccessful)
{
	GEngine->AddOnScreenDebugMessage(-1, 10.f, FColor::Red, FString::Printf(TEXT("OnStartSessionComplete %s, %d"), *SessionName.ToString(), bWasSuccessful));

	// Get the Online Subsystem so we can get the Session Interface
	IOnlineSubsystem* OnlineSub = IOnlineSubsystem::Get();
	if (OnlineSub)
	{
		// Get the Session Interface to clear the Delegate
		IOnlineSessionPtr Sessions = OnlineSub->GetSessionInterface();
		if (Sessions.IsValid())
		{
			// Clear the delegate, since we are done with this call
			Sessions->ClearOnStartSessionCompleteDelegate_Handle(OnStartSessionCompleteDelegateHandle);
		}
	}

	// If the start was successful, we can open a NewMap if we want. Make sure to use "listen" as a parameter!
	if (bWasSuccessful)
	{
		UGameplayStatics::OpenLevel(GetWorld(), "NewMap", true, "listen");
	}
}
```

Similar to the first one, we get, check and clear things. Then, if everything is done and the process was again successful, we open a new Level with "listen" as a parameter. This is important!

And that's it. Now we created a Session and started it, so we are ready to get Clients on our Server/Session. But for that we need them to find our Session. So next up is "Finding Sessions".

### Searching and Finding a Session

So, once we are sure that somewhere we have a Session we can find, we can proceed with the following code.

**Searching and Finding a Session | Header File**

Function to setup our search and start the searching:

```cpp
// In our UNWGameInstance.h:

/**
*	Find an online session
*
*	@param UserId user that initiated the request
*	@param bIsLAN are we searching LAN matches
*	@param bIsPresence are we searching presence sessions
*/
void FindSessions(TSharedPtr<const FUniqueNetId> UserId, bool bIsLAN, bool bIsPresence);
```

A delegate and a handle for it:

```cpp
// In our UNWGameInstance.h:

/** Delegate for searching for sessions */
FOnFindSessionsCompleteDelegate OnFindSessionsCompleteDelegate;

/** Handle to registered delegate for searching a session */
FDelegateHandle OnFindSessionsCompleteDelegateHandle;
```

A variable for our SearchSettings which will also contain our SearchResults, once this search is complete and successful:

```cpp
// In our UNWGameInstance.h:

TSharedPtr<class FOnlineSessionSearch> SessionSearch;
```

And finally the function we want to bind to the delegate:

```cpp
// In our UNWGameInstance.h:

/**
*	Delegate fired when a session search query has completed
*
*	@param bWasSuccessful true if the async action completed without error, false if there was an error
*/
void OnFindSessionsComplete(bool bWasSuccessful);
```

**Searching and Finding a Session | CPP File**

Now filling this with logic similar to the creation process:

```cpp
// In our UNWGameInstance.cpp:

void UNWGameInstance::FindSessions(TSharedPtr<const FUniqueNetId> UserId, bool bIsLAN, bool bIsPresence)
{
	// Get the OnlineSubsystem we want to work with
	IOnlineSubsystem* OnlineSub = IOnlineSubsystem::Get();

	if (OnlineSub)
	{
		// Get the SessionInterface from our OnlineSubsystem
		IOnlineSessionPtr Sessions = OnlineSub->GetSessionInterface();

		if (Sessions.IsValid() && UserId.IsValid())
		{
			/*
				Fill in all the SearchSettings, like if we are searching for a LAN game and how many results we want to have!
			*/
			SessionSearch = MakeShareable(new FOnlineSessionSearch());

			SessionSearch->bIsLanQuery = bIsLAN;
			SessionSearch->MaxSearchResults = 20;
			SessionSearch->PingBucketSize = 50;
			
			// We only want to set this Query Setting if "bIsPresence" is true
			if (bIsPresence)
			{
				SessionSearch->QuerySettings.Set(SEARCH_PRESENCE, bIsPresence, EOnlineComparisonOp::Equals);
			}

			TSharedRef<FOnlineSessionSearch> SearchSettingsRef = SessionSearch.ToSharedRef();

			// Set the Delegate to the Delegate Handle of the FindSession function
			OnFindSessionsCompleteDelegateHandle = Sessions->AddOnFindSessionsCompleteDelegate_Handle(OnFindSessionsCompleteDelegate);
			
			// Finally call the SessionInterface function. The Delegate gets called once this is finished
			Sessions->FindSessions(*UserId, SearchSettingsRef);
		}
	}
	else
	{
		// If something goes wrong, just call the Delegate Function directly with "false".
		OnFindSessionsComplete(false);
	}
}
```

Getting OnlineSubsystem etc and filling the SearchSettings variable. Then setting the Delegate to the handle and tell the SessionInterface to "FindSessions". That's all (:

Once this is finished, the Delegate functions is called. We still need to connect these in the Constructor:

```cpp
// In our UNWGameInstance.cpp:

/** Bind function for FINDING a Session */
OnFindSessionsCompleteDelegate = FOnFindSessionsCompleteDelegate::CreateUObject(this, &UNWGameInstance::OnFindSessionsComplete);
```

And the function logic:

```cpp
// In our UNWGameInstance.cpp:

void UNWGameInstance::OnFindSessionsComplete(bool bWasSuccessful)
{
	GEngine->AddOnScreenDebugMessage(-1, 10.f, FColor::Red, FString::Printf(TEXT("OFindSessionsComplete bSuccess: %d"), bWasSuccessful));

	// Get OnlineSubsystem we want to work with
	IOnlineSubsystem* const OnlineSub = IOnlineSubsystem::Get();
	if (OnlineSub)
	{
		// Get SessionInterface of the OnlineSubsystem
		IOnlineSessionPtr Sessions = OnlineSub->GetSessionInterface();
		if (Sessions.IsValid())
		{
			// Clear the Delegate handle, since we finished this call
			Sessions->ClearOnFindSessionsCompleteDelegate_Handle(OnFindSessionsCompleteDelegateHandle);

			// Just debugging the Number of Search results. Can be displayed in UMG or something later on
			GEngine->AddOnScreenDebugMessage(-1, 10.f, FColor::Red, FString::Printf(TEXT("Num Search Results: %d"), SessionSearch->SearchResults.Num()));
		
			// If we have found at least 1 session, we just going to debug them. You could add them to a list of UMG Widgets, like it is done in the BP version!
			if (SessionSearch->SearchResults.Num() > 0)
			{
				// "SessionSearch->SearchResults" is an Array that contains all the information. You can access the Session in this and get a lot of information.
				// This can be customized later on with your own classes to add more information that can be set and displayed
				for (int32 SearchIdx = 0; SearchIdx < SessionSearch->SearchResults.Num(); SearchIdx++)
				{
					// OwningUserName is just the SessionName for now. I guess you can create your own Host Settings class and GameSession Class and add a proper GameServer Name here.
					// This is something you can't do in Blueprint for example!
					GEngine->AddOnScreenDebugMessage(-1, 10.f, FColor::Red, FString::Printf(TEXT("Session Number: %d | Sessionname: %s "), SearchIdx+1, *(SessionSearch->SearchResults[SearchIdx].Session.OwningUserName)));
				}
			}
		}
	}
}
```

After getting the OnlineSubsystem and the SessionInterface, we clear the DelegateHandle again and now we can work with the SearchResults. They are stored in the "SessionSearch" variable we created. "SessionSearch->SearchResults" is an array with all found Sessions. You can get several information from this and later on maybe create your own child class of this to add more information! I'm just printing them to the Screen.

That's all for finding Sessions. Now we can go on and try to join one.

### Joining a Session

There are different ways you can Join a session, but we will just use a Session result which we can get from the SearchResult array and joined it with help of the SessionInterface. As easy as possible.

**Joining a Session | Header file**

So the function we are going to use:

```cpp
// In our UNWGameInstance.h:

/**
*	Joins a session via a search result
*
*	@param SessionName name of session
*	@param SearchResult Session to join
*
*	@return bool true if successful, false otherwise
*/
bool JoinSession(TSharedPtr<const FUniqueNetId> UserId, FName SessionName, const FOnlineSessionSearchResult& SearchResult);
```

The delegates and the function that we bind to it:

```cpp
// In our UNWGameInstance.h:

/** Delegate for joining a session */
FOnJoinSessionCompleteDelegate OnJoinSessionCompleteDelegate;

/** Handle to registered delegate for joining a session */
FDelegateHandle OnJoinSessionCompleteDelegateHandle;
```

```cpp
// In our UNWGameInstance.h:

/**
*	Delegate fired when a session join request has completed
*
*	@param SessionName the name of the session this callback is for
*	@param bWasSuccessful true if the async action completed without error, false if there was an error
*/
void OnJoinSessionComplete(FName SessionName, EOnJoinSessionCompleteResult::Type Result);
```

Nothing fancy as Settings here. Just the functions and the delegates.

**Joining a Session | CPP file**

```cpp
// In our UNWGameInstance.cpp:

bool UNWGameInstance::JoinSession(TSharedPtr<const FUniqueNetId> UserId, FName SessionName, const FOnlineSessionSearchResult& SearchResult)
{
	// Return bool
	bool bSuccessful = false;

	// Get OnlineSubsystem we want to work with
	IOnlineSubsystem* OnlineSub = IOnlineSubsystem::Get();

	if (OnlineSub)
	{
		// Get SessionInterface from the OnlineSubsystem
		IOnlineSessionPtr Sessions = OnlineSub->GetSessionInterface();

		if (Sessions.IsValid() && UserId.IsValid())
		{
			// Set the Handle again
			OnJoinSessionCompleteDelegateHandle = Sessions->AddOnJoinSessionCompleteDelegate_Handle(OnJoinSessionCompleteDelegate);
			
			// Call the "JoinSession" Function with the passed "SearchResult". The "SessionSearch->SearchResults" can be used to get such a
			// "FOnlineSessionSearchResult" and pass it. Pretty straight forward!
			bSuccessful = Sessions->JoinSession(*UserId, SessionName, SearchResult);
		}
	}
		
	return bSuccessful;
}
```

We are doing nothing new here. Since we have no settings, we are not filling any. We are just taking the SearchResult that was passed and call "JoinSession" once we set the delegate to the handle.

And once this is finished, our function gets called again. Again, don't forget to bind it in the constructor:

```cpp
// In our UNWGameInstance.cpp:

/** Bind function for JOINING a Session */
OnJoinSessionCompleteDelegate = FOnJoinSessionCompleteDelegate::CreateUObject(this, &UNWGameInstance::OnJoinSessionComplete);
```

```cpp
// In our UNWGameInstance.cpp:

void UNWGameInstance::OnJoinSessionComplete(FName SessionName, EOnJoinSessionCompleteResult::Type Result)
{
	GEngine->AddOnScreenDebugMessage(-1, 10.f, FColor::Red, FString::Printf(TEXT("OnJoinSessionComplete %s, %d"), *SessionName.ToString(), static_cast<int32>(Result)));

	// Get the OnlineSubsystem we want to work with
	IOnlineSubsystem* OnlineSub = IOnlineSubsystem::Get();
	if (OnlineSub)
	{
		// Get SessionInterface from the OnlineSubsystem
		IOnlineSessionPtr Sessions = OnlineSub->GetSessionInterface();

		if (Sessions.IsValid())
		{
			// Clear the Delegate again
			Sessions->ClearOnJoinSessionCompleteDelegate_Handle(OnJoinSessionCompleteDelegateHandle);

			// Get the first local PlayerController, so we can call "ClientTravel" to get to the Server Map
			// This is something the Blueprint Node "Join Session" does automatically!
			APlayerController * const PlayerController = GetFirstLocalPlayerController();

			// We need a FString to use ClientTravel and we can let the SessionInterface contruct such a
			// String for us by giving him the SessionName and an empty String. We want to do this, because
			// Every OnlineSubsystem uses different TravelURLs
			FString TravelURL;

			if (PlayerController && Sessions->GetResolvedConnectString(SessionName, TravelURL))
			{
				// Finally call the ClienTravel. If you want, you could print the TravelURL to see
				// how it really looks like
				PlayerController->ClientTravel(TravelURL, ETravelType::TRAVEL_Absolute);
			}
		}
	}
}
```

Here we are doing something new. After getting the OnlineSubsystem and the SessionInterface, we clear the handle. Then we get the PlayerController of the joining Player. Since we are still on this Player, we can just get the FirstLocal one.

The we create an FString that will hold the TravelURL, which we need for a ClientTravel to the Map of the Server. How do we get the TravelURL? Easy: We tell the SessionInterface to create us one. Just pass the SessionName (which at this point is already the one of the Session we joined!) and the FString. Then we can call the ClientTravel function of the PlayerController and we are on the ServerMap, ready to play!

But now we need to also be able to destroy a Session. This is important, because Sessions take Slots on Servers and prevent us from creating new ones or join others as long as they exist.

### Destroying a Session

Destroying a Session doesn't need an extra function from us, since we don't need settings or something like that. So we only need the delegate, handle and delegate function:

**Destroying a Session | Header file**

```cpp
// In our UNWGameInstance.h:

/** Delegate for destroying a session */
FOnDestroySessionCompleteDelegate OnDestroySessionCompleteDelegate;

/** Handle to registered delegate for destroying a session */
FDelegateHandle OnDestroySessionCompleteDelegateHandle;
```

```cpp
// In our UNWGameInstance.h:

/**
*	Delegate fired when a destroying an online session has completed
*
*	@param SessionName the name of the session this callback is for
*	@param bWasSuccessful true if the async action completed without error, false if there was an error
*/
virtual void OnDestroySessionComplete(FName SessionName, bool bWasSuccessful);
```

**Destroying a Session | CPP file**

Binding the function in the Constructor!

```cpp
// In our UNWGameInstance.cpp:

/** Bind function for DESTROYING a Session */
OnDestroySessionCompleteDelegate = FOnDestroySessionCompleteDelegate::CreateUObject(this, &UNWGameInstance::OnDestroySessionComplete);
```

And filling the function with logic:

```cpp
// In our UNWGameInstance.cpp:

void UNWGameInstance::OnDestroySessionComplete(FName SessionName, bool bWasSuccessful)
{
	GEngine->AddOnScreenDebugMessage(-1, 10.f, FColor::Red, FString::Printf(TEXT("OnDestroySessionComplete %s, %d"), *SessionName.ToString(), bWasSuccessful));

	// Get the OnlineSubsystem we want to work with
	IOnlineSubsystem* OnlineSub = IOnlineSubsystem::Get();
	if (OnlineSub)
	{
		// Get the SessionInterface from the OnlineSubsystem
		IOnlineSessionPtr Sessions = OnlineSub->GetSessionInterface();

		if (Sessions.IsValid())
		{
			// Clear the Delegate
			Sessions->ClearOnDestroySessionCompleteDelegate_Handle(OnDestroySessionCompleteDelegateHandle);

			// If it was successful, we just load another level (could be a MainMenu!)
			if (bWasSuccessful)
			{
				UGameplayStatics::OpenLevel(GetWorld(), "ThirdPersonExampleMap", true);
			}
		}
	}
}
```

Doing the same with the OnlineSubsystem and the SessionInterface again and once the destruction was successful, we Open the start level again, which could be the MainMenu for example.

And that's it, this is all you need for a basic setup. You can now create Widgets or so that can use these functions, **BUT** you can't make these functions BlueprintCallable. You need a second function for each process that is BlueprintCallable.

## BlueprintCallable Functions to test this Setup

### Creating a Session

```cpp
// In our UNWGameInstance.h:

UFUNCTION(BlueprintCallable, Category = "Network|Test")
void StartOnlineGame();
```

```cpp
// In our UNWGameInstance.cpp:

void UNWGameInstance::StartOnlineGame()
{
	// Creating a local player where we can get the UserID from
	ULocalPlayer* const Player = GetFirstGamePlayer();
	
	// Call our custom HostSession function. GameSessionName is a GameInstance variable
	HostSession(Player->GetPreferredUniqueNetId(), GameSessionName, true, true, 4);
}
```

### Searching and Finding a Session

```cpp
// In our UNWGameInstance.h:

UFUNCTION(BlueprintCallable, Category = "Network|Test")
void FindOnlineGames();
```

```cpp
// In our UNWGameInstance.cpp:

void UNWGameInstance::FindOnlineGames()
{
	ULocalPlayer* const Player = GetFirstGamePlayer();

	FindSessions(Player->GetPreferredUniqueNetId(), true, true);
}
```

### Joining a Session

```cpp
// In our UNWGameInstance.h:

UFUNCTION(BlueprintCallable, Category = "Network|Test")
void JoinOnlineGame();
```

```cpp
// In our UNWGameInstance.cpp:

void UNWGameInstance::JoinOnlineGame()
{
	ULocalPlayer* const Player = GetFirstGamePlayer();

	// Just a SearchResult where we can save the one we want to use, for the case we find more than one!
	FOnlineSessionSearchResult SearchResult;

	// If the Array is not empty, we can go through it
	if (SessionSearch->SearchResults.Num() > 0)
	{
		for (int32 i = 0; i < SessionSearch->SearchResults.Num(); i++)
		{
			// To avoid something crazy, we filter sessions from ourself
			if (SessionSearch->SearchResults[i].Session.OwningUserId != Player->GetPreferredUniqueNetId())
			{
				SearchResult = SessionSearch->SearchResults[i];

				// Once we found sounce a Session that is not ours, just join it. Instead of using a for loop, you could
				// use a widget where you click on and have a reference for the GameSession it represents which you can use
				// here
				JoinSession(Player->GetPreferredUniqueNetId(), GameSessionName, SearchResult);
				break;
			}
		}
	}	
}
```

### Destroying a Session

```cpp
// In our UNWGameInstance.h:

UFUNCTION(BlueprintCallable, Category = "Network|Test")
		void DestroySessionAndLeaveGame();
```

```cpp
// In our UNWGameInstance.cpp:

void UNWGameInstance::DestroySessionAndLeaveGame()
{
	IOnlineSubsystem* OnlineSub = IOnlineSubsystem::Get();
	if (OnlineSub)
	{
		IOnlineSessionPtr Sessions = OnlineSub->GetSessionInterface();

		if (Sessions.IsValid())
		{
			Sessions->AddOnDestroySessionCompleteDelegate_Handle(OnDestroySessionCompleteDelegate);

			Sessions->DestroySession(GameSessionName);
		}
	}
}
```


# Spawn Different Pawns For Players in Multiplayer

This wiki article was written by TheJamsh.

### Overview

In this tutorial, I'll show you how I use C++ to allow a player to spawn into a Multiplayer game with a Pawn of their choice. By default, Unreal Engine allows you to choose a Pawn class that every player will use. We will change this functionality so that the Clients (and Server) can choose their Pawn way before they are spawned into the world.

### Step 1: Custom Game Mode

To start with, we need to override the 'GetDefaultPawnClassForController' function in AGameMode. Normally this function simply returns the GameModes 'DefaultPawnClass', but we want to change this so that it can hook into our custom Player Controller, and read the value from there.

**This is a much more flexible approach than creating lots of Pawn Variables in the GameMode, since we can specify any pawn class we want from our PlayerController this way!**

**MyGameMode.h**

```cpp
UCLASS()
class MYGAME_API AMyGameMode : public AGameMode
{
	GENERATED_UCLASS_BODY()
 
	/* Override To Read In Pawn From Custom Controller */
	UClass* GetDefaultPawnClassForController(AController* InController) override;
};
```

**MyGameMode.cpp**

```cpp
AMyGameMode::AMyGameMode(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer)
{
	/* Use our custom Player-Controller Class */
	PlayerControllerClass = AMyPlayerController::StaticClass();
}
 
UClass* AMyGameMode::GetDefaultPawnClassForController(AController* InController)
{
	/* Override Functionality to get Pawn from PlayerController */
	AMyPlayerController* MyController = Cast<AMyPlayerController>(InController);
	if (MyController)
	{
		return MyController->GetPlayerPawnClass();
	}
 
	/* If we don't get the right Controller, use the Default Pawn */
	return DefaultPawnClass;
}
```

Intellisense/Visual Assist will warn you that 'GetPlayerPawnClass()' doesnt' exist yet. Fear not, we'll create that in the next section!

### Step 2: Custom Player Controller

We must now invoke some custom functionality in our PlayerController, in order to tell the Gamemode which Pawn to use. On this rare occasion, we actually want the Client to have authority over the Server to ensure the Client chooses the Pawn locally, and tell the server to do the rest.

My method sets a Replicated Variable on the Server, the value of which is determined on the Client beforehand. This way, we take advantage of UE4s authoritative server system, keeping the two players in-sync and ensuring that no client-side cheating can ever occur. The server still handles the spawning of the Pawn, and the developer can choose to further validate the Clients choice if they want to.

**NOTE:** The method posted below determines which Pawn to use based on an external .txt file. This is purely because it suited our implementation, but I do NOT recommend following this method for almost any other game, since the file can be easily modified by an end user. It would be much safer and more flexible, to use a SaveGame class generated inside the game itself, and have the server verify that the Pawn is a valid option server-side.

Saving the correct Pawn to use as a SaveGame is outside the scope of this tutorial, but you can study ShooterGame's **ShooterPersistentUser** class to learn more about how to use them. Simply replace the body of 'DeterminePawnClass' with code that loads the Pawn class from your custom SaveGame.

**MyPlayerController.h**

```cpp
UCLASS()
class MYGAME_API AMyPlayerController : public APlayerController
{
	GENERATED_BODY()
 
public:
	/* Constructor */
	AMyPlayerController(const FObjectInitializer& ObjectInitializer);
 
	FORCEINLINE UClass* GetPlayerPawnClass() { return MyPawnClass; }
 
protected:
	/* Return The Correct Pawn Class Client-Side */
	UFUNCTION(Reliable, Client)
	void DeterminePawnClass();
	virtual void DeterminePawnClass_Implementation();
 
	/* Use BeginPlay to start the functionality */
	virtual void BeginPlay() override;
 
	/* Set Pawn Class On Server For This Controller */
	UFUNCTION(Reliable, Server, WithValidation)
	virtual void ServerSetPawn(TSubclassOf<APawn> InPawnClass);
	virtual void ServerSetPawn_Implementation(TSubclassOf<APawn> InPawnClass);
	virtual bool ServerSetPawn_Validate(TSubclassOf<APawn> InPawnClass);
 
	/* Actual Pawn class we want to use */
	UPROPERTY(Replicated)
	TSubclassOf<APawn> MyPawnClass;
 
	/* First Pawn Type To Use */
	UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "My Controller")
	TSubclassOf<AGESGame_ServerPawn> PawnToUseA;
 
	/* Second Pawn Type To Use */
	UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "My Controller")
	TSubclassOf<AGESGame_Pawn> PawnToUseB;
};
```

**MyPlayerController.cpp**

```cpp
AMyPlayerController::AMyPlayerController(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer)
{
	/* Initialize The Values */
	PawnToUseA= NULL;
	PawnToUseB= NULL;
 
	/* Make sure the PawnClass is Replicated */
	bReplicates = true;
}
 
void AMyPlayerController::BeginPlay()
{
	Super::BeginPlay();
 
	DeterminePawnClass();
}
 
// Pawn Class
void AMyPlayerController::DeterminePawnClass_Implementation()
{
	if (IsLocalController()) //Only Do This Locally (NOT Client-Only, since Server wants this too!)
	{
		/* Load Text File Into String Array */
		TArray<FString> TextStrings;
		const FString FilePath = FPaths::GameDir() + "Textfiles/PlayerSettings.txt";
 
	        /* Use PawnA if the Text File tells us to */
		if (TextStrings[0]== "PawnA")
		{
			ServerSetPawn(PawnToUseA);
			return;
		}
 
	        /* Otherwise, Use PawnB :) */
		ServerSetPawn(PawnToUseB);
		return;
	}
}
 
bool AMyPlayerController::ServerSetPawn_Validate(TSubclassOf<APawn> InPawnClass)
{
	return true;
}
 
void AMyPlayerController::ServerSetPawn_Implementation(TSubclassOf<APawn> InPawnClass)
{
	MyPawnClass = InPawnClass;
 
	/* Just in case we didn't get the PawnClass on the Server in time... */
	GetWorld()->GetAuthGameMode()->RestartPlayer(this);
}
 
// Replication
void AMyPlayerController::GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const
{
	DOREPLIFETIME(AMyPlayerController, MyPawnClass);
}
```

### Client/Server Functions

The **most important functionality** in the Player Controller is NOT necessarily how you determine which pawn to use, but is actually the use of Client/Server functions and the Replicated 'MyPawnClass' variable. Without this, the Server will never know which Pawn the Client wants to spawn.

Also note the use of 'IsLocalPlayerController()' during the 'DeterminePawnClass' function. This is a check to ensure that the Server doesn't try to load it's own TextFile for the player, and ensures that the Client tells the Server which Pawn it wants to use, not the other way around. Without it, all of the players will actually end up using the Servers' chosen Pawn, regardless of what they really want to do! Don't replace this with an Authority check, since the Server could also be a player!

### Text File Implementation

If you want to use this functionality exactly as it's posted above, you need to create a folder in your projects' Root Directory called 'TextFiles', and in there create a new .txt file called 'PlayerSettings.txt'

The Player Controller will search for the file on BeginPlay and attempt to load the text inside it into an array of strings. Each line in the text file forms another element in the array. If the first line in the text file is 'PawnA', the controller will tell the GameMode to use 'PawnToUseA' for this player. If any other value is entered or no value is found, it will instead use 'PawnToUseB'.

### Assertion

I **Strongly Recommend** you add additional checks and/or asserts to the above code. The final code that I actually use does have this in place, but I used an alternative Assert Library that I do not have permission to share, and so cut them out. Remember, you should always check if something valid and never allow your code to de-reference a NULL pointer!

If a .txt file isn't found for the example posted above, it will crash the engine. If you want to build a packaged version of your game, you **must** copy the TextFiles folder into the games' folder when packaging has finished!

### Final Word

I do NOT encourage the use of TextFiles to determine which pawn to use for a real project. The code above is only meant to show the order of operations, and the use of Client/Server functionality to ensure reliability. It was suitable only for a very unique implementation. I highly recommend modifying the 'DeterminePawnClass' function to return a Pawn class from a SaveGame, or similar. This method is much more secure and less prone to errors.

In due time, I will update this tutorial to do exactly that, as I believe it is much more suited to most projects. More advanced C++ users will be able to integrate this on their own from this point on however, so enjoy!

Hope this helps!


# Spawn Different Pawns For Every Player

Not every player is likely going to use DefaultPawnClass as their Pawn and my quick search through the UE4 community didn't result in any information. The Shooter example touches on this but only handles the difference between AI and Player, and not what to do if you have multiple Pawns that a player can select.

The first question I had when starting into this was where to store the information that tells the server what player is using what Pawn. I think the reason I struggled with this for so long was simply because the class that really holds information about a player is named APlayerController and that led me to believe that I really should only be using it for input from the player. So very very wrong. The APlayerController class is perfectly suited for this usage.

So the first thing I did was create a new struct to hold information about the players chosen Pawn. In the example below I only have one int32 as a property, but in our actual code we're storing much more about the Pawn that is required at spawn such as items the player may have equipped. For the purposes of this tutorial though the below is enough.

```cpp
struct PlayerPawnData
{
	int32 Type;
};
```

Then inside your custom [APlayerController](https://web.archive.org/web/20161008074957/https://docs.unrealengine.com/latest/INT/API/Runtime/Engine/GameFramework/APlayerController/index.html) declaration you'd want to define a public property that uses this struct as it's type.

```cpp
PlayerPawnData CurrentPawnData;
```

With this data now available in your APlayerController declaration lets move to the custom AGameMode you've defined for your UE4 game.

There are a few functions inside AGameMode that are important to respawning a player. The first is RestartPlayer and the name of this function should make it's use pretty self-explanatory. This function is called when a player spawns, whether it's when they've first joined or just died. The functions that are called inside RestartPlayer is what we're going to focus on, primarily GetDefaultPawnClassForController.

The basic functionality of GetDefaultPawnClassForController simply returns the member variable DefaultPawnClass but for this game that isn't going to work since each player could have a different Pawn class. That means we're going to have to override this function entirely. Lets start with the declaration inside your custom AGameMode class.

```cpp
virtual UClass* GetDefaultPawnClassForController(AController* InController) OVERRIDE;
```

We'll also need some sort of storage so we can reference the Pawn class using the type provided inside the PlayerPawnData variable on the APlayerController.

```cpp
TMapBase<int32, UClass*, false> PawnTypes;
```

So we've marked GetDefaultPawnClassForController as an override and we have a place to store our pawn types now lets create the functionality. Same as the examples above I've simplified the code for this tutorial. We've got a little more going on inside our GetDefaultPawnClassForController.

```cpp
UClass* AMyGameMode::GetDefaultPawnClassForController(AController* InController)
{
	AMyPlayerController* PlayerController = Cast<AMyPlayerController>(InController);

	UClass* PawnClass = PawnTypes.Find(PlayerController->CurrentPawnData.Type);

	return PawnClass;
}
```

So what's happening above? We're casting the incoming AController into our custom APlayerController and then referencing the CurrentPawnData's property Type to find the correct Pawn to spawn. With just this overridden the UE4 base AGameMode class will start spawning the correct Pawn when the player joins or dies.

I'm sure there's a different way to go about doing this but this felt right to me. Storing the actual UClass would be an option but because in our specific use case we're storing more than just the UClass to spawn but also base stats pertaining to that Pawn type I went with just storing the type.

Reposted from [http://www.osnapgames.com/2014/06/17/spawn-different-pawns-depending-on-player-selection/](https://web.archive.org/web/20161008074957/http://www.osnapgames.com/2014/06/17/spawn-different-pawns-depending-on-player-selection/)


# Gameplay Abilities and You

This wiki article was written by KJZ in a forum post.

## Introduction

*This is here for archival reasons, however, there are more updated resources such as the* [*GASDocumentation*](https://github.com/tranek/GASDocumentation) *and* [*GASShooter*](https://github.com/tranek/GASShooter) *repos*

So, what's a GameplayAbility?

Basically, they're like the abilities you have in Dota or equivalent games. You can cast a fireball, and this fireball hits a player, explodes (doing a set amount of damage), and sets everyone in the radius of the explosion on fire (doing damage over time). Meanwhile, the player who cast the fireball loses some mana and is put on cooldown.

You could use Epic's GameplayAbility plugin to do all of those things. The module is hard to wrap your head around, but once you learn how powerful they can be and how to properly make use of them, they can make your life much, much easier.

But why use this over rolling your own system?

GameplayAbilities can come in handy if your game is in need of a powerful skill, buff and attribute system that is both easy to extend and crazy-efficient to replicate. This can do wonders for people working on a multiplayer RPG with a lot of skills/classes or perhaps even a MOBA, but you can use this system for pretty much any game you want. The main problem is that it isn't the easiest to comprehend, quite big and may get a little in your way the further you stray too far away from this multiplayer RPG ideal, so not every game will get the same mileage out of it.

Well, that sounds like a dream, but where do I get it?

Well, first of all, GameplayAbilities is a code module that used to be integrated into UE4's source, but since this current version (4.15, that is, people from the future) has been moved into a separate plugin that is delivered alongside the Unreal Engine, so that it may not take away space in your games if they do not make use of the system. This system does not actually originate as a built-in engine feature, but has, in fact, been kindly left in there from the developers of Paragon and Fortnite for third parties to enjoy. Unfortunately, due to these unique circumstances, the module as a whole is quite messy, poorly (read: barely at all, your best bet are code comments and even those are only there like half the time) documented, and rarely updated and cleaned up.

It is also not 100% exposed to blueprints, partially, but not entirely, due to a lot of the system abusing a lot of engine trickery and magic to work as well as they do, so if you never worked with C++ in the context of UE4, you may want to turn back and maybe do a little tutorial on that now, because this tutorial will make for a poor first learning experience.

In other words, it is a total flippin' pain in the buttocks to wrap your head around, but that's where this guide comes in to help ya. [Epic Developer Dave Ratti has an example GitHub project](https://github.com/daveratti/GameplayAbilitiesSample) which goes through some basic examples to get you started, but ignores the fine lines and goes for broad strokes. The project itself has been pretty hidden, however, and (at the time) doesn't really show up on Google or any real search about the GameplayAbilities plugin, so it hasn't been as helpful as a full-fledged guide. Moreover, now that GameplayTags are properly integrated into the editor by default (a system GameplayAbilities itself uses at every corner of the way, acting as GameplayAbilities' backbone), setup has never been any easier!

With all that said, let's get started, finally.

## Getting Started

### Setting up the project

So, first of all, let us create an all-new C++ third person project, not just because I want you to properly understand the specifics of enabling the system for your own use, but also because I want to start on a clean slate so that you may not be confused by assets which you do not have on hand.

![Project Creation](https://github.com/NickGlenn/Unreal-Engine-4-Community-Guide/tree/58f38c224a525dc8480d25ca361411d9d3e3ff4c/.gitbook/assets/gameplayabilities-project-creation.png)

This should be a fairly straightforward and obvious step to anyone that has ever created a UE4 C++ project before. I'm calling it GameplayAbilitiesTut, but you may call it as you'd like, really, as long as you pay attention and replace my project's name with yours while coding and understanding. Alright, we're here. Good old third person template, such a familiar environment, and so useful for tutorials! We want to open the plugin menu, accessed through the Settings tab.

![Plugins](https://github.com/NickGlenn/Unreal-Engine-4-Community-Guide/tree/58f38c224a525dc8480d25ca361411d9d3e3ff4c/.gitbook/assets/enabling-plugins.png)

We find GameplayAbilities in the Gameplay category. Enable it. Do not be scared off by the big scary "\[UNSUPPORTED]" in the description or the prompt that asks you if you're sure. You know darn well you're sure! You must now restart the editor to fully enable the plugin. It contains a few menus and a new blueprint type to select from the new asset-menu, but it won't load those until the next restart.

After you restart, you may or may not notice a few new things: A new blueprint type called "Gameplay Ability Blueprint" when you press right-click in the content browser to create a new blueprint and a new window in the window menu called "GameplayCue Editor".

![Cue Editor](https://github.com/NickGlenn/Unreal-Engine-4-Community-Guide/tree/58f38c224a525dc8480d25ca361411d9d3e3ff4c/.gitbook/assets/gameplaycue-editor.png)

![Ability Blueprint](https://github.com/NickGlenn/Unreal-Engine-4-Community-Guide/tree/58f38c224a525dc8480d25ca361411d9d3e3ff4c/.gitbook/assets/gameplayability-blueprint.png)

We don't go into specifics with these just yet, but we do want to create a Gameplay Ability Blueprint, mostly because it's pretty much just a generic blueprint for abilities, and we will need one to test our AbilitySystemComponent later.

Select "GameplayAbility" as your blueprint's parent, name it Use\_Spell\_1, open the blueprint and just link a Print String node to the ActivateAbility event. Now you know when your AbilitySystem successfully calls your ability, because then a reassuring light-blue "Hello." will show on the screen. Self-explanatory, really.

### Setting up our Character

Alright, I hope you got your Visual Studio ready already, it's time for some nitty gritty code. We want to give our character an ability component to use.

... well, not quite, anyway. We need to tell our compiler that we want to use the GameplayAbilities module first. Go into your project's `Build.cs` file(in my case it's `GameplayAbilitiesTut.Build.cs`) and change this

```csharp
PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore", "HeadMountedDisplay" });
```

to this

```csharp
PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore", "HeadMountedDisplay", "GameplayAbilities" });
```

Basically, we add "GameplayAbilities" to the list. Don't worry about getting it wrong, your compiler will immediately start nagging if it can't find the module with the name you typed in. Adding the module name into this list assures that the module will be properly linked to our project. Without it our compiler would throw out a bunch of confusing external linker errors each time we were to include a header from this module into our project's files.

Now, open your project's C++ character. This will be GameplayAbilitiesTutCharacter for me. Go into the class header and declare a new pointer to a UAbilitySystemComponent right below your other component pointers. You should also give it a UPROPERTY macro. It's okay to copy and paste the UPROPERTY from your camera components, but you should probably change the category to something like "Abilities" for clarity reasons. It should look a little like this.

```cpp
/** Camera boom positioning the camera behind the character */
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Camera, meta = (AllowPrivateAccess = "true"))
class USpringArmComponent* CameraBoom;

/** Follow camera */ UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Camera, meta = (AllowPrivateAccess = "true"))
class UCameraComponent* FollowCamera;

/** Our ability system */ UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Abilities, meta = (AllowPrivateAccess = "true"))
class UAbilitySystemComponent* AbilitySystem;
```

What is also extremely important, so we don't get into trouble later down the line, is to make it so that our character implements the `IAbilitySystemInterface`. The guide assumes basic programming knowledge, you should know about what an interface does, so I won't get too much into detail, but it allows us to define a pseudo-parent of sorts that defines functions we have to override. This interface here gives other actors an easy way to both know we have an ability system, and a way to get it without doing something dumb and inefficient like iterating through our components for an ability system. Many features will not run properly without this interface implemented. Our code until now would run fine without it, but you will head into trouble once we're done with our initial setup and want to throw buffs and similar things on our character.

```cpp
#include "AbilitySystemInterface.h" //We add this include.

UCLASS(config=Game)
class AGameplayAbilitiesTutCharacter : public ACharacter, public IAbilitySystemInterface //We add this parent.
{
    UAbilitySystemComponent* GetAbilitySystemComponent() const override //We add this function, overriding it from IAbilitySystemInterface.
    {
        return AbilitySystem;
    };
}
```

Further, we go into our cpp file and go to the constructor of your character. For me that is `GameplayAbilitiesTutCharacter.cpp`. We need to actually create the component, and have our pointer point to it. As you will actually create an object of type `UAbilitySystemComponent` now, you must include `"AbilitySystemComponent.h"` in your cpp file. Top of the file up to constructor should look a little like this now.

```cpp
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
include "GameplayAbilitiesTut.h"
include "Kismet/HeadMountedDisplayFunctionLibrary.h"
include "GameplayAbilitiesTutCharacter.h"
include "AbilitySystemComponent.h"
////////////////////////////////////////////////////////////////////////// // AGameplayAbilitiesTutCharacter

AGameplayAbilitiesTutCharacter::AGameplayAbilitiesTutCharacter()
{ 
    // Set size for collision capsule
    GetCapsuleComponent()->InitCapsuleSize(42.f, 96.0f);
    // set our turn rates for input
    BaseTurnRate = 45.f;
    BaseLookUpRate = 45.f;

    // Don't rotate when the controller rotates. Let that just affect the camera.
    bUseControllerRotationPitch = false;
    bUseControllerRotationYaw = false;
    bUseControllerRotationRoll = false;

    // Configure character movement
    GetCharacterMovement()->bOrientRotationToMovement = true;

    // Character moves in the direction of input...
    GetCharacterMovement()->RotationRate = FRotator(0.0f, 540.0f, 0.0f);

    // ...at this rotation rate
    GetCharacterMovement()->JumpZVelocity = 600.f;
    GetCharacterMovement()->AirControl = 0.2f;

    // Create a camera boom (pulls in towards the player if there is a collision)
    CameraBoom = CreateDefaultSubobject<USpringArmComponent>(TEXT("CameraBoom"));
    CameraBoom->SetupAttachment(RootComponent);
    CameraBoom->TargetArmLength = 300.0f; // The camera follows at this distance behind the character 
    CameraBoom->bUsePawnControlRotation = true; // Rotate the arm based on the controller

    // Create a follow camera
    FollowCamera = CreateDefaultSubobject<UCameraComponent>(TEXT("FollowCamera"));
    FollowCamera->SetupAttachment(CameraBoom, USpringArmComponent::SocketName); // Attach the camera to the end of the boom and let the boom adjust to match the controller orientation
    FollowCamera->bUsePawnControlRotation = false; // Camera does not rotate relative to arm

    // Our ability system component.
    AbilitySystem = CreateDefaultSubobject<UAbilitySystemComponent>(TEXT("AbilitySystem"));

    // Note: The skeletal mesh and anim blueprint references on the Mesh component (inherited from Character)
    // are set in the derived blueprint asset named MyCharacter (to avoid direct content references in C++)
}
```

You may try to compile if you are unsure whether you did everything the right way.

Once you have compiled, you can open your character blueprint(which inherits from your C++ character) and lo and behold, right under the character's movement component you should see an `AbilitySystemComponent`.

![Ability System Component Added](https://github.com/NickGlenn/Unreal-Engine-4-Community-Guide/tree/58f38c224a525dc8480d25ca361411d9d3e3ff4c/.gitbook/assets/abilitysystemcomponent-added.png)

Alright, well... what now? The blueprint menu for the component is not helpful at all, and none of the nodes you get by dragging off AbilitySystem are particularly useful, either. There's these "Try Activate Ability" nodes, but you may find out that these things don't do anything right now. That's because the ability system doesn't have any abilities to activate yet, nor does it have any inputs assigned to them, anyway, so trying to activate an ability you do not have is, obviously, a quite useless effort. We will work on fixing both things. You must do both things in C++.

### Binding to Character Input

First of all, we will bind our ability system to our character's input, because it's the slightly more complicated issue and it's actually pretty interesting on how you do it. So first of all, go back to your character's cpp file, and go to the SetupPlayerInputComponent function. It's the one responsible for binding your character's inputs to the player controlling it, and takes a UInputComponent as parameter. This is important, we need it to bind our ability system to it. We want to call AbilitySystem->BindAbilityActivationToInputComponent within the SetupPlayerInputComponent. It takes two parameters: The UInputComponent pointer at hand and a struct called `FGameplayAbiliyInputBinds`. ***This is not a typo!*** It is not called **FGameplayAbilityInputBinds**, but **FGameplayAbiliyInputBinds!**

***Note: Latest as of 4.24 this typo has been fixed.***

The constructor for `FGameplayAbiliyInputBinds` takes at least 3 parameters: The first two are strings, and represent the input names that will be used to define "Confirm" and "Cancel"-input commands. You do not necessarily need these depending on your game, but abilities can be set up to listen to these while they're active, and targeting actors (basically, actors that return an ability viable targets/locations to aim at for an ability, if an ability requests one) will use these too, so generally it can't hurt to have these even if you will never use them. The third parameter is the name of an arbitrary UEnum of all things. This is one of the witchcraft-ier aspects of the system: The ability system component will look into the enum whose name you've given and will map its ability slots to the names of the elements contained within the enum. This probably sounds way complicated from the way I'm describing this, but it's actually quite simple. This is an input enum lifted from my own project:

```cpp
//Example for an enum the FGameplayAbiliyInputBinds may use to map input to ability slots.
//It's very important that this enum is UENUM, because the code will look for UENUM by the given name and crash if the UENUM can't be found. BlueprintType is there so we can use these in blueprints, too. Just in case. Can be neat to define ability packages.
UENUM(BlueprintType) 
enum class AbilityInput : uint8
{
    UseAbility1 UMETA(DisplayName = "Use Spell 1"), //This maps the first ability(input ID should be 0 in int) to the action mapping(which you define in the project settings) by the name of "UseAbility1". "Use Spell 1" is the blueprint name of the element.
    UseAbility2 UMETA(DisplayName = "Use Spell 2"), //Maps ability 2(input ID 1) to action mapping UseAbility2. "Use Spell 2" is mostly used for when the enum is a blueprint variable.
    UseAbility3 UMETA(DisplayName = "Use Spell 3"),
    UseAbility4 UMETA(DisplayName = "Use Spell 4"),
    WeaponAbility UMETA(DisplayName = "Use Weapon"), //This finally maps the fifth ability(here designated to be your weaponability, or auto-attack, or whatever) to action mapping "WeaponAbility".
    //You may also do something like define an enum element name that is not actually mapped to an input, for example if you have a passive ability that isn't supposed to have an input. This isn't usually necessary though as you usually grant abilities via input ID,
    //which can be negative while enums cannot. In fact, a constant called "INDEX_NONE" exists for the exact purpose of rendering an input as unavailable, and it's simply defined as -1.
    //Because abilities are granted by input ID, which is an int, you may use enum elements to describe the ID anyway however, because enums are fancily dressed up ints.
}
```

Basically, this means we need to define an enum, too. Let's just do it in our `GameplayAbilitiesTutCharacter`'s header. You may copy-paste this enum here if you wish, (and this tutorial will do just that), even if 5 slots may be a little overkill for the purpose of example. Finally, our function should look something like this:

```cpp
AbilitySystem->BindAbilityActivationToInputComponent(PlayerInputComponent, FGameplayAbiliyInputBinds("ConfirmInput", "CancelInput", "AbilityInput"));
```

Place this code at the end of your `SetupPlayerInputComponent` function, and you should be gravy. You have successfully bound your ability system's ability activation to player input!

### Giving the Character an Ability

The final step of our setup is to finally give the character an ability of choice. For simplicity's sake we will only give him one on the action mapping "UseAbility1" and just give the actor a variable that defines which ability to put there, but the same principles for granting one ability are applicable for multiple ones. We will make it blueprint-editable too so we can easily change the ability we want to test later down the line.

Our variable will be a `TSubclassOf<UGameplayAbility>`, because we get all relevant info from the class alone. In fact, GameplayAbilities can be set up to only instance per activation or not to instance at all even, so giving an instance we can freely change beforehand would be a weird idea, anyway.

```cpp
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Abilities)
TSubclassOf<class UGameplayAbility> Ability;
```

In BeginPlay, we will call AbilitySystem's `GiveAbility` function. We actually wrap this in an if-statement that first checks if we are authority. If a client tries to give himself an ability, an assert is violated and the game goes to crash and burn, taking the editor with it. You've been warned. Only give abilities on the server... or else! We'll also need to check if Ability is valid, and not NULL/nullptr.

`GiveAbility` requests an `FGameplayAbilitySpec` as parameters. An `FGameplayAbilitySpec` is the data surrounding a `GameplayAbility`, notably which level (the system has built-in support for a level variable, quite good for RPGs/MOBAs as mentioned) and which input ID it is.

`FGameplayAbilitySpec` requests a `GameplayAbility` object as parameter, but that's not a problem; we can just give the Ability class' default object as parameter. There is very little reason to use anything other than the default object of a `GameplayAbility` class as far as I've understood it from going through the source. Finally, while on the topic of BeginPlay, we should also call `AbilitySystem->InitAbilityActorInfo`. It tells the AbilitySystem what its Owner (the actor responsible for the AbilitySystem) and Avatar (the actor through which the AbilitySystem acts, uses Abilities from etc.) is. In our case our character is both. Our final BeginPlay should look something like this:

```cpp
void AGameplayAbilitiesTutCharacter::BeginPlay()
{

  Super::BeginPlay();
  if(AbilitySystem)
  {
     if (HasAuthority() && Ability)
     {
        AbilitySystem->GiveAbility(FGameplayAbilitySpec(Ability.GetDefaultObject(), 1, 0));
     }
     AbilitySystem->InitAbilityActorInfo(this, this);
  }
}
```

You also need to make sure that the AbilitySystemComponent's ActorInfo struct is being updated each time the controller changes. On the surface much of the system will work without that, but in a multiplayer enviroment especially(where pawns may be spawned before the client controller possesses them) you will experience crashes and behaviour that can be difficult to debug should you not properly set the ActorInfo up. Override your character's/pawn's OnPossessed function like so:

```cpp
void AGameplayAbilitiesTutCharacter::PossessedBy(AController * NewController)
{
   Super::PossessedBy(NewController);
   AbilitySystem->RefreshAbilityActorInfo();
}
```

Compile, add an action input mapping in your project settings called "UseAbility1" and start the game. If the game doesn't crash and the mapped input produces a plain old "Hello.", then congratulations! You have successfully set up your gameplay ability system for this character.

Note that if it crashes and spits out an error message talking about AbilityActorInfo being invalid, try adding this code just before the HasAuthority() check and seeing if it fixes the problem:

```cpp
FGameplayAbilityActorInfo* actorInfo = new FGameplayAbilityActorInfo();
actorInfo->InitFromActor(this, this, AbilitySystem); 
AbilitySystem->AbilityActorInfo = TSharedPtr<FGameplayAbilityActorInfo>(actorInfo);
```

That was the worst and dryest part, so you are allowed to be proud of yourself! We can finally move on to the actually exciting part of using the system.

## The Essentials

Alright, you should now have at least one functional GameplayAbility bound to your character, which is pretty cool. However, we haven't even gotten into what GameplayAbilities can do yet. Heck, we haven't gotten to what anything at all does yet, because setup took so long. However, GameplayAbilities are a great place to start general comprehension.

### GameplayAbilities

#### Overview

GameplayAbilities are the stupidly flexible implementation of spells, skills and such in this system. Not only do they have easy support for such things as cooldown, costs and other common RPG-ish stock spell features, but they are set up in such a way that you may call so-called Ability Tasks within them. These are specialized asynchronous tasks that you may request to run during an ability's active period, returning to the blueprint graph once the task has completed its task, or until a certain event or passage of time prompts the task to call back.

They're in a sense very much like your run-of-the-mill Blueprint Delay node, but they can do oh-so-much-more than just waiting a certain amount of time to continue. They may, for instance, wait for an input, or for a collision/overlap, or for a montage to finish playing(going to a different execution path when ending normally or when interrupted), they can even wait for client and server to sync up to a certain point. This means that an ability must not immediately be done after the initial activation frame, but may consist of one to several different time-consuming processes before finally being finished.

Wait for an animation to finish playing before firing a fireball? Easy. Charge the fireball by holding down the button mapped to the ability, releasing the button to fire the fireball? Easy. Heck, you could probably program an ability that forces you to play DDR with your fingers before shooting a fireball, with the fireball getting stronger with godlike finger dancing skills, if you really wanted to.

This comes at a small price though, because an ability activation always needs to directly or indirectly call EndAbility to announce that its Activation has ended. By default you will be unable to trigger an activation past the first one (though there is an option to be able to reset a running ability when pressing the activate-button), and it will be considered permanently active for all intents and purposes. This may mess with other abilities or aspects of the system. You must also manually call "Commit Ability" within the ability activation, which checks for and applies the likes of cost and cooldowns.

An ability is also able to control its own instancing state, and each ability may independently choose whether they do not want to be instanced (no ability tasks, no personal state and variables and some other limited functionality, but ridiculously cheap so preferable if you can get away with it), instanced on activation (personal state limited to a per-activation basis, variables and such can be replicated but it is not recommended) or instanced per ability owner (most expensive, but variables can easily be replicated, state can be carried across activations \[for example, a fireball that gets stronger with each use would be possible without permanently considering the ability active] and most functions are intact).

Finally, abilities can be useful for certain passive effects too, as abilities can listen for tags being granted upon their owners or Gameplay Events firing in the owning Ability System Component (more on that another time). Buffs that respond to certain outside influences may implement themselves by granting the affected actor with a hidden passive ability to listen for these, for example.

As such, GameplayAbilities are extremely useful, and you'd do good to learn how to best make use of them.

**Notable Variables**

* **Ability Tags:** Gameplay Tags the ability uses as flags, so to speak. Gameplay Tags are pretty much a global list of names and terms that can be used by assets as generic names and labels. In the context of GameplayAbilities these can be useful by having a GameplayAbility use an Ability Task to listen for the activation of a different ability with specified tag as ability tag.
  * Alternatively, an ability may cancel other currently active abilities that are described to have ability tag X, or it may be blocked from activating while ability with ability tag X is active. These are easy ways to set up global behaviour and interaction between different abilities. Perhaps only one transformation can be active at a time? Perhaps activating fire magic while water magic is active cancels one or both? It's up to you and what type of game you want to make. There are no strict rules.
* **Cancel Ability with Tags:** Abilities with these tags will be cancelled upon activation of this ability.
* **Block Ability with Tags:** Abilities with these tags will be blocked while this ability here is active.
* **Activation Owned Tags:** The Owner of the ability gets these tags while the ability is active. This is something different than **Ability Tags**, because the owner gets these here. GameplayEffects (buffs) may interact with them this way, and other abilities can, as already mentioned, listen for a tag to be granted to its owner to active. This has a lot of uses if you get creative with it, you could make the user of the ability immune to damage while they are casting this, etc.
* **Activation Required Tags:** The Owner has to have these tags ***BEFOREHAND*** so that it may become activatable. Great for, say, buffs that allow you access to strong abilities, or perhaps status effect-purging abilities that are only activatable as you are affected by the status effect at hand.

  Activation Blocked Tags: Same as Activation Required Tags but in reverse: the Owner of the ability must not have these tags. Excellent for crowd control effects such as silences, stuns, roots (which, in some games, disable movement-related abilities), you name 'em.
* **Source Required Tags:** The source must have these tags. What the system considers "source tags" is not immediately obvious because it isn't explained anywhere, but you can trigger abilities with payloads containing this information using a feature called GameplayEvents, which are detailed much further down below. The GameplayEvent will pass a struct which you can fill out as you please beforehand, with the InstigatorTags in that struct acting as the tags used in the Source Required and Source Blocked checks. When the payload contains all tags here specified in some capacity, the ability activation is allowed.
* **Source Blocked Tags:** See **Source Required Tags**. Same applies, but instead of checking if all described tags are present, it checks if none of the blocked tags are present in the payload. If a blocking tag is present, the activation will be stopped.
* **Target Required Tags:** See **Source Required Tags**. Same rules apply, but the tag container "TargetTags" from the GameplayEvent payload is used. It stands to reason that the InstigatorTags should be filled out with either the currently applied or at least descriptive tags of the actor owning the ability and firing it, and the TargetTags should be filled out with info relevant to who will get hit by this ability activation. As the code doesn't really enforce how you're filling out the tag containers in the GameplayEvent data however, you're free to do whatever you like, really.
* **Target Blocked Tags:** Same as **Target Required Tags** but with Blocked tags.
* **Cost GameplayEffect:** This is a GameplayEffect (in a sense a buff, or instant stat modifying action) that may contain instant, and thus permanent, stat modifiers, for example for mana and stamina and such. This checks if the attribute in question will be lowered below 0 by one such instant modifier. If so, Commit Ability will prompt the ability to end prematurely.
* **Ability Triggers:** Can be used for remote ability activation. You can choose to activate the ability in response to a tag being granted to the owner, the tag being present on the owner (ending the ability automatically when the tag ceases applying(?)), or a Gameplay Event labelled with the specified tag being handled by the ability's owning Ability System Component.
* **Cooldown GameplayEffect:** This GameplayEffect represents the ability's cooldown. When checking for cooldown, the ability will look into this gameplay effect's granted tag container (the tags it may grant to the owner while active) and will then check if the using ability system has any of these tags granted to them. If yes, the ability will be considered on cooldown.
  * This essentially means that all independent cooldowns need their own dedicated gameplay tag, but it also means that multiple abilities can easily share a cooldown, outside events may easily set a particular cooldown and one ability may also have a gameplay effect sharing cooldowns with 2 different kinds of cooldowns that do not influence each other.
  * A cooldown gameplay effect can also be set to 0/really low so that you may set the cooldown manually with the tags specified in the dedicated cooldown GameplayEffect as the ability is running, which can be useful if your ability doesn't always have a predictable and predefined cooldown in mind.

### GameplayTasks

#### Overview

Fairly self-explanatory; AbilityTasks are Blueprint nodes you can call in Ability graphs that wait for an outside stimuli before continuing. AbilityTasks inherit from so-called GameplayTasks, which generally have very similar usages that involve calling a blueprint node that may call back to the graph later, but while GameplayTasks are intended for much more general usage that covers things from giving an AI commands to follow to completion to simply acting as slightly expanded Delay node, AbilityTasks are specialized for usage within(and only within) GameplayAbilities. AbilityTasks usually possess an unlabelled top exec route that you may use to continue calling functions within the current frame and labelled exec pins that will run its attached route of functions at a later time, much like how delays work but with things other than time, usually.

They usually do what they advertise in their name/description, they support multiplayer because the server will generally always call them because the ability itself will generally always be called on the server, and will do their best predicting because the client will usually call them first unless specified otherwise by you. They do not actually have innate systems for correcting predictions on their own, but the things you do change with them usually will be replicated/will have systems to prevent desyncs themselves, so for the built-in tasks this is rarely a problem. Still, you should be wary of that when writing your own task classes.

Tasks will only run for as long as the ability is active, so the `EndAbility` node will prematurely end all pending ability tasks originating from that ability, as well. Because of this, you probably want to place things that **HAVE** to happen, no matter how the ability ended, in the EndAbility function. One example I could think off probably being purging off a buff that roots you in place as you play your casting animation.

Furthermore, because abilities have to remain active to use their tasks and abilities can really only track their state for their current activation, this also means that, for example, projectiles with elaborate effects should try to find a workaround over constantly keeping the ability active until they hit something/cease to exist, unless said projectile actively occupies the character or there is other similar reasons ability duration and projectile lifetime have to be so tightly knit together.

The rest of this section will be about creating your own custom task. You are free to skip to the usage example for Blueprints further down below for now if you have no reason to create your own task at the moment. You won't exactly have to make your own custom task often, this bit here is mostly so you don't feel too lost if you have to actually do one yourself.

Creating an AbilityTask is relatively simple, but it's not immediately obvious how you're supposed to do it. It's also not actually needed unless you have an outside system you need to incorporate into abilities somehow, and that has any meaningful callbacks to send back to these abilities. I personally have created a custom ability task for a melee attack system component that I intend to use, that first plays an attack montage and then calls back using delegates each time a new enemy has been hit by an attack's hitbox, and finally when the montage ends and the attack ceases. With these delegate callbacks it is possible to implement custom on-hit logic from the comfort inside your ability and still let the melee system do all the heavy lifting for you. Being able to have bigger procedures and actions be all handled within a compact and easy task node while you just have to implement what happens after which events is a huge boon and a big reason to use them where they make sense!

First, you must include the GameplayTask module in your build files. GameplayTasks are the overarching system AbilityTasks use to create asynchrous nodes in abilities, so trying to create new AbilityTasks without adding this module first will usually result in Linker errors:

```cpp
PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore", "HeadMountedDisplay", "GameplayAbilities", "GameplayTasks"} );
```

Now create your AbilityTask object in the UE4 C++ file explorer. I'm calling mine AbilityTask\_MyTask, but you may want to rename it depending on what you want it to do. You know the drill.

Once you have created a new, empty class that inherits from AbilityTask, you should first of all define a static function in there that will help creating the AbilityTask within an ability BP. Technically you can put this static function anywhere really, but having it in your class is easy and makes it easy to find if you need to change it, too.

They're all set up about the same way, just a static function taking an OwningAbility, a task name and some optional extra variables(depending on usage) as parameters, returning a task of the type you want to return, with the UFUNCTION properties further easing and streamlining it for BP use:

```cpp
/* This UFUNCTION macro describes, in that order:
The function can be called in BP, the category in which 
the function will de displayed in the BP-function-
dropdown is "Ability", subcategory "Tasks", the function 
name in BP is displayed as "ExecuteMyTask",
the pin for the parameter "OwningAbility" is hidden in BP 
and the parameter "OwningAbility" will default to 
the object the calling graph belongs to, if applicable. 
Finally, BlueprintInternalUseOnly = "TRUE" prevents
a regular function node for this UFUNCTION to be created, 
which makes sense because this function needs to use
an async task node instead(which has some added behaviour 
on being called such as actually activating the 
task, extra exec pins, etc). */
UFUNCTION(BlueprintCallable, Category = "Ability|Tasks", meta = (DisplayName = "ExecuteMyTask", HidePin = "OwningAbility", DefaultToSelf = "OwningAbility", BlueprintInternalUseOnly = "TRUE"))
static UAbilityTask_MyTask* CreateMyTask(UGameplayAbility* OwningAbility, FName TaskInstanceName, float examplevariable);
```

The cpp code is fairly straightforward, you simply create a task using the dedicated NewAbilityTask constructor function, initialize its values as you see fit and then return it. The blueprint node itself will usually do the rest of the job activating and keeping track of it, etc.:

```cpp
UAbilityTask_MyTask* UAbilityTask_MyTask::CreateMyTask(UGameplayAbility * OwningAbility, FName TaskInstanceName, float examplevariable)
{
    UAbilityTask_MyTask* MyObj = NewAbilityTask->UAbilityTask_MyTask->(OwningAbility, TaskInstanceName);
    //Just assume we have defined a float called OptionalValue somewhere in the class before. This is just an example.
    MyObj->OptionalValue = examplevariable;
    return MyObj;
}
```

Compile and, if everything has been done correctly, you should now have a new task function by the name of "ExecuteMyTask"(or your custom name) to use in your ability BPs. It doesn't have any new exec pins we could use though. Let us fix that!

While the exact logic behind how and why async task nodes work remain nebulous to me, creating new exec pins is actually rather easy in practice. First you need to define a dynamic multicast delegate. Multicast delegates are basically special structs you can wire functions into to call later upon "broadcasting" the delegate. These macros require a name for the new type of delegate you want to define, and they also need a list of parameter types and their corresponding names if your delegate is supposed to take functions that take at least one parameter themselves(as the delegate will then call these functions with the parameters it is broadcasted with). This all probably sounds very strange and complicated just written out like that, but it is actually rather easy when you see the code:

```cpp
//This lets you create a delegate with no parameters by the struct name of "FMyDelegate".
DECLARE_DYNAMIC_MULTICAST_DELEGATE(FMyDelegate);

//So if you want to have a class with a delegate variable of that type, you'd declare it as
FMyDelegate DelegateVariable;

//Finally, if you want to call all functions wired to DelegateVariable, you call
DelegateVariable.Broadcast();

/* You're not limited to just no-parameter functions either, a delegate 
that takes functions with a first parameter float and a second parameter int 
looks like this: */
DECLARE_DYNAMIC_MULTICAST_DELEGATE_TwoParams(FMyTwoParamDelegate, float, FirstParamName, int32, SecondParamName);

//You would then broadcast it like, for example:
TwoParamDelegateVariable.Broadcast(20.f, 15);
```

How does this detour help us? Simple, an async task node will look for the first UPROPERTY dynamic multicast delegate variable it finds in your AbilityTask class and use it as the delegate type for its extra outgoing exec pins from that point. Check out this code for example:

```cpp
DECLARE_DYNAMIC_MULTICAST_DELEGATE_TwoParams(FMyTwoParamDelegate, float, FirstParamName, int32, SecondParamName);
UCLASS()
class WIZARDMP_API UAbilityTask_MyTask : public UAbilityTask
{
    GENERATED_BODY()
    //The important bit here.
    UPROPERTY(BlueprintAssignable)
    FMyTwoParamDelegate OnCalled;

        UFUNCTION(BlueprintCallable, Category = "Ability|Tasks", meta = (DisplayName = "ExecuteMyTask", HidePin = "OwningAbility", DefaultToSelf = "OwningAbility", BlueprintInternalUseOnly = "TRUE"))
        static UAbilityTask_MyTask* CreateMyTask(UGameplayAbility* OwningAbility, FName TaskInstanceName, float examplevariable);

    /* This function will call after the BP node has successfully requested the 
    ability task from the static function. You put your actual 
    functionality here. More on that in a bit. */
    virtual void Activate() override;
};
```

The async node will now have a new outgoing exec pin labelled "OnCalled" right under its regular exec pin, and there will even be pins for a float and an int value right below said exec pin, which you may now use to decide further action with inside your ability BP!

Do note that you may only have one multicast delegate type as dedicated exec pin delegate. If you were to have multiple multicast delegate types used in your class, the first one takes priority and the variables using the other types will not show up! Henceforth you should make sure that your delegate covers the variable needs of all your possible output execution pins. Better to have a pin occassionally unused than not having enough to convey all the important info your ability may need.

Broadcasting the delegate variable will now also fire off the exec pin in the BP. Usually you will have a different function within your class that you can wire up to some kind of different delegate, TimerHandle or any similar thing so you can wait for a particular thing to happen before broadcasting your main delegate. Unfortunately this example has no actual usage scenario in mind, so we will simply just broadcast the delegate right in the Activate function instead:

```cpp
void UAbilityTask_MyTask::Activate()
{
    /* This is the part where you'd set up different delegates, timers etc. to prepare the task
    to eventually broadcast OnCalled sometime later. We have nothing prepared in this tutorial 
    task however, so we may as well just call OnCalled right within the Activate function instead. */
    OnCalled.Broadcast(500.f, 42);
}
```

With that, your first task should be complete! This example is quite barebones, but should showcase everything important you need to know when making your own, real task to use in conjunction with your own systems. In case you are still a bit unsure about certain things, you can use the folder with the ability tasks contained within the plugin itself for further directions and pointers on how to do certain things. Godspeed!

#### GameplayTasks Example

Here is an example Blueprint graph of using a `GameplayAbilityTargetActor_SingleLineTrace` to do a "hitscan"-type weapon. It fires a ray from the player's origin in the direction they're looking (handled by the GameplayTask). When it hits something, it reports back to the Blueprint graph. The Blueprint graph then draws a pink line based on the origin and ending points of the line trace and ends the ability.

![Hitscan Weapon](https://github.com/NickGlenn/Unreal-Engine-4-Community-Guide/tree/58f38c224a525dc8480d25ca361411d9d3e3ff4c/.gitbook/assets/gameplayabilitiesandyou/Hitscan_Weapon.png)

You could go farther and use the struct provided from the output of `GameplayAbilityTargetActor_SingleLineTrace` to determine which Pawn you hit (if any) and apply a **GameplayEffect** to it, reducing its health or applying buffs of some kind. Speaking of GameplayEffects...

### GameplayEffects

#### Overview

**GameplayEffects** can be described as this system's dedicated buff class. Their functionality goes a little beyond that, and in fact most stat modifiers regardless of instant and permanent or over time and temporary are usually GameplayEffects. They're very peculiar in how they are set up to work as they are built to be hyper-efficient to replicate/network in general.

As such GameplayEffects are, first and foremost, glorified struct-like data assets with in-blueprint inheritance and without the ability to change their variables during runtime, as they will often be passed by class reference alone. In fact, you will almost NEVER see a plain GameplayEffect being passed around in code and especially not in Blueprint. The tooltip says they're data-only, and they really do mean that.

GameplayEffects usually use `GameplayEffectSpecs` to move around, which are huge behemoths of structs that store everything from effect context (what level, who is instigator, who is target, which ability spawned me, why do I even exist?) to reference to the GameplayEffect class that defines most default behaviour and variables to stack count to potential extra modifiers/tags/whatever to pass in alongside what the class reference defines upon applying. In a strange sort of way, `GameplayEffectSpecs` are much closer to object instances than the GameplayEffect instances themselves are. As such, if you want to apply a gameplay effect via ability, either apply it directly through a class reference or create a `GameplayEffectSpec` within the ability and use that to apply a GameplayEffect.

**Notable Variables** Due to the unusual nature of Gameplay Effect blueprint classes, most of their variables are either simple values, other direct class references or just tags. There are too many to list and after explaining how abilities and their tags work, it should be fairly self-explanatory what most tags are used for, or do. It should however be noted that Gameplay Effects have 3 containers for each type of tag, one that is not directly editable, one that describes tags added on top of tags potentially owned from a parent and tags that are removed from a potential parent. Basically, this tag inheritance setup is one of relatively few reasons why Gameplay Effects are full-fledged UObject classes in the first place. Some of the more notable variables are:

* **Duration Policy:** Is the effect instant, does it have a fixed duration, or does it go on infinitely? Do note that instant effects turn modifiers into permanent stat changes, and executions will be triggered immediately.

  Modifiers: Stat changes in all shapes and forms. Whether you want to add a flat amount to a stat, multiply a stat, divide, override with a fixed value or do any of these things in relation to other stats.
* **Executions:** Executions are an interesting case: They are essentially the functions the gameplay effect itself can't have (due to being meant to be as data-only as possible). An Execution takes a GameplayEffectExecutionCalculation as parameter, a class that is set up to define attributes to capture from both target and source, and to do things with them that would be considered too complex with modifiers alone. They are more or less meant to do as they please, however they cannot listen to events and such like abilities can do and pretty much only run in fixed, predefined intervals on timed GameplayEffects (and optionally once on application), or immediately on application in the case of instant GameplayEffects. They're your go-to for complex damage calculation and the likes. More on that later.
* **Stacking:** You know how in some games certain buffs/debuffs of one kind can stack on a target? This behaviour is managed here. By default all GameplayEffects of the same type will act and tick down independently (though requesting the amount of stacks of a gameplay effect will usually still show the total amount of effect instances of this type). There are options to make them all go on the same timer, removing one stack each time duration runs out, removing all of them once the timer runs out once, if application of a new stack refreshes the current duration or if there is a cap on stacks. You can get quite creative with these.
* **Overflow:** Adding up on stacks, overflow effects are essentially effects that the affected actor will be affected by when the max amount of stacks of this gameplay event has been reached. If you get cold enough you freeze, breathe enough poison gas to get heavily poisoned, whatever, you get it.
* **Display:** You can define GameplayCues to use here. At their most basic, GameplayCues are essentially visual/audible effects that respond to a specialized tag they've been assigned to. It needs to have "GameplayCue" as its parent tag, so an example tag could be "GameplayCue.DoT.Fire". You can call these directly in abilities too. They're a network-friendly way to spawn stuff like particle effects, cosmetic meshes and sound effects to provide your debuffs and skills with some eye candy. How they react to being called by the GameplayEffect/Ability is defined within the GameplayCue itself (there's 4 types of events a GameplayCue will respond to: OnActive (Called when a GameplayCue is activated), WhileActive (Called when GameplayCue is active, even if it wasn't actually just applied, eg. Join in progress), Removed (when... well, removed) and Executed (This will be called when a GameplayEffect's execute classes run via instant effects or periodic tick).
* **GrantedAbilities:** This has many uses. You may use a buff to temporarily provide an active ability as part of the buff(maybe a fire mage can give someone else a fire ability by igniting one of his allies? Heh, gotta love combat arson), but, more importantly, you can use these for effects that are too specific for modifiers but need to be permanently active in a way effect executions can't. If a gameplay effect is tagged to grant an actor an "OnFire" tag, you may have an ice buff with a passive ice ability granted listen for this event and remove the offending effect, as well as the ice buff itself (GameplayAbilities have a function just to allow them to remove the effect that granted them). Together with modifiers and executions, this allows you to do virtually anything with your effects.

It should be noted that most float values put into are not actually just plain float values, but rather a struct called **FScalableFloat**. You can use it just like any regular float, but there is an asset pointer to the right of the box where you'd put the float value in. It may confuse you because there are no valid references to use, and there is no option to create a new one. This slot is reserved for a **Curve Table**, an asset you get by importing a csv, or file with a comparable table file format, into the project.

***This is one of the few things where effect level makes a difference***, as the table will then look at the column labelled with this level (or the columns it should be between, determining the value dependent on what kind of graph the table row is set to describe) so if you use levels in, for example, your GameplayEffectExecutionCalculations, keep that in mind, as you may accidentally set a value to scale in unexpected ways otherwise.

#### GameplayEffects Example

Let's make an example of perhaps the simplest use case for GameplayEffects: Cooldowns. Below, we have a very simple GameplayAbility that prints "Hello", puts itself on cooldown, then ends the ability.

![Cooldown Ability](https://github.com/NickGlenn/Unreal-Engine-4-Community-Guide/tree/58f38c224a525dc8480d25ca361411d9d3e3ff4c/.gitbook/assets/gameplayabilitiesandyou/CooldownAbility.png)

The part circled in blue is the GameplayEffect which signals that we are on cooldown. When this GameplayEffect is applied to us, the ability is unusable.

The part circled in red is the GameplayEffect that gets applied to us when we use this ability. In this example, it's just something that puts us on cooldown right away, but we could make it so using an ability slows us down for a little bit, or starts stacking GameplayEffects until we reach a maximum amount, at which point another GameplayEffect is applied which causes us to actually go on cooldown (which could be a simple example of using GameplayAbilities for a weapon/ammo system).

Now we move on to the GameplayEffect itself.

![Cooldown Gameplay Effect](https://github.com/NickGlenn/Unreal-Engine-4-Community-Guide/tree/58f38c224a525dc8480d25ca361411d9d3e3ff4c/.gitbook/assets/gameplayabilitiesandyou/CooldownGameplayEffect.png)

The part in red sets this to be a GameplayEffect which happens over a duration (5 seconds in this example). At the end of this duration, the GameplayEffect is lifted. That's all this example does; it just applies itself for 5 seconds.

The part in blue is where all the magic happens. An FGameplayTag "AbilityTags.Cooldown" is applied to our AbilitySystemComponent while this GameplayEffect is active. This is how our AbilitySystemComponent knows which GameplayEffects are active. When you try to activate the sample GameplayAbility above, it checks to see if you have the tags in blue. If you do, then nothing happens -- it won't let you activate the ability. Otherwise, the ability works. The tags in there can be called whatever you want; these ones just happen to be called "`AbilityTags.Cooldown`".

#### AttributeSet

**AttributeSets** are thankfully very simple to explain. They define float values (and ONLY float values. Right now only float attributes are supported) and can be connected to AbilitySystems to grant the ability system in question these attributes. GameplayEffects and GameplayEffectExecutionCalculations have specifically designed macros and menus to manipulate these attributes on an ability system. An ability system may use multiple attribute sets or none at all, too.

The system accounts for attributes it cannot find and will simply ignore stats that are not appropriate for the particular actor and his AbilitySystem. As such, maybe both players and foes have Health, Mana, attack damage, defense, you name 'em, and players then have an extra attribute set containing RPG attributes such as Strength, Intelligence, Constitution and the like. These are all perfectly possible scenarios, and it's nice that the system gives you the option to mix and match multiple attribute sets. The best way to bind an attribute set to an ability system is to create the AttributeSet as the same actor's subobject in the constructor. The ability system should find it by itself. It does for me, at least.

Attributes within attribute sets are defined like any other UPROPERTY, which is amazingly practical and straightforward. Why can't everything in this module be... Well, it isn't that easy anyway, due to the AttributeSet's functions, which either deal with finding out which UPROPERTY the current parameter is talking about or have to do with the infinitely more complex GameplayEffectExecutionCalculation.

**PreAttributeBaseChange** is called before... well, an attribute's base value (so without any temporary modifiers) is changed. It would be unwise to use this for game logic, and is mostly there to allow you to describe stat clamping.

**PreAttributeChange** is in the same boat, but here you can define clamping with temporary modifiers instead. Either way, NewValue describes the new value of a changed stat, and FGameplayAttribute Attribute describes some info about the stat we're talking about. If you want to find out if this particular Attribute change is talking about a particular Attribute MyAttribute in UMyAttributeSet, you'd do it something like this:

```cpp
Attribute.GetUProperty() == FindFieldChecked<UProperty>(UMyAttributeSet::StaticClass(), GET_MEMBER_NAME_CHECKED(UMyAttributeSet, MyAttribute))
```

This code takes the UPROPERTY variable of the Attribute parameter and checks if the referenced UPROPERTY is identical with the one that describes MyAttribute in UMyAttributeSet. The macro is mostly there for safety, I believe this is actually defined as a relatively simple string.

**PreGameplayEffectExecute** is a function that takes the data a GameplayEffectExecutionCalculation spits out (including which stats it wishes to modify, and by how much), and can then decide if the GameplayEffectExecutionCalculation is allowed to influence the AttributeSet in any way, by returning an appropriate bool. PostGameplayEffectExecute happens after this evaluation and as such you are unable to throw the GameplayEffectExecution out properly by then. However, because 90% of the time things such as damage calculations will be effect executions, here will be an excellent place to wrap such a thing up, such as by, for example, checking if the damage you took killed you.

#### Using AttributeSets

So, now that we understand what Attributes are and how they work, let's take a look at a simple "Health" attribute.

This is some simple code, which just gives an AbilitySystemComponent a "Health" value:

```cpp
UCLASS()
class UMyAttributeSet : public UAttributeSet
{
    GENERATED_BODY()
public: 
//Hitpoints. Self-explanatory.
UPROPERTY(Category = "Wizard Attributes | Health", EditAnywhere, BlueprintReadWrite)
FGameplayAttributeData Health;

//FGameplayAttributeData is the intended struct to be used for attributes by the system. However,
//attributes can also be declared as simple floats. I am unsure if the attribute initialization method
//further down functions with the struct, however the float method seems to be the more dated one.

}
```

That's it! Easy, right?

But as of right now, that health value doesn't do anything. You can tell the ability system that you have some health, but it doesn't know what to do when your health hits 0 (and indeed, in the above example, your health IS 0 -- you might want to add a constructor or something to set it to a reasonable value). That's where the functions like PostGameplayEffectExecute that we just learned about come into play!

Here's some code taken from Dave Ratti's example GitHub project linked at the beginning of the article:

```cpp
void UGASAttributeSet::PostGameplayEffectExecute(const struct FGameplayEffectModCallbackData& Data)
{
    UAbilitySystemComponent* Source = Data.EffectSpec.GetContext().GetOriginalInstigatorAbilitySystemComponent();
    if (HealthAttribute() == Data.EvaluatedData.Attribute)
    {
        // Get the Target actor
        AActor* DamagedActor = nullptr;
        AController* DamagedController = nullptr;
        if (Data.Target.AbilityActorInfo.IsValid() && Data.Target.AbilityActorInfo->AvatarActor.IsValid())
        {
            DamagedActor = Data.Target.AbilityActorInfo->AvatarActor.Get();
            DamagedController = Data.Target.AbilityActorInfo->PlayerController.Get();
        }
        // Get the Source actor
        AActor* AttackingActor = nullptr;
        AController* AttackingController = nullptr;
        AController* AttackingPlayerController = nullptr;
        if (Source && Source->AbilityActorInfo.IsValid() && Source->AbilityActorInfo->AvatarActor.IsValid())
        {
            AttackingActor = Source->AbilityActorInfo->AvatarActor.Get();
            AttackingController = Source->AbilityActorInfo->PlayerController.Get();
            AttackingPlayerController = Source->AbilityActorInfo->PlayerController.Get();
            if (AttackingController == nullptr && AttackingActor != nullptr)
            {
                if (APawn* Pawn = Cast<APawn>(AttackingActor))
                {
                    AttackingController = Pawn->GetController();
                }
            }
        }
        // Clamp health
        Health = FMath::Clamp(Health, 0.0f, MaxHealth);
        if (Health <= 0)
        {
            // Handle death with GASCharacter. Note this is just one example of how this could be done.
            if (AGASCharacter* GASChar = Cast<AGASCharacter>(DamagedActor))
            {
                // Construct a gameplay cue event for this death
                FGameplayCueParameters Params(Data.EffectSpec.GetContext());
                Params.RawMagnitude = Data.EvaluatedData.Magnitude;
                Params.NormalizedMagnitude = FMath::Abs(Data.EvaluatedData.Magnitude / MaxHealth);
                Params.AggregatedSourceTags = *Data.EffectSpec.CapturedSourceTags.GetAggregatedTags();
                Params.AggregatedTargetTags = *Data.EffectSpec.CapturedTargetTags.GetAggregatedTags();
                GASChar->Die(DamagedController, DamagedActor,  Data.EffectSpec, Params.RawMagnitude, Params.Normal);
            }
        }
    }
}
```

You can see how things start getting a little more complex, but really, it's nothing you can't handle! `HealthAttribute()` is defined using that same macro we used earlier:

```cpp
FGameplayAttribute UGASAttributeSet::HealthAttribute()
{
    static UProperty* Property = FindFieldChecked<UProperty>(UGASAttributeSet::StaticClass(), GET_MEMBER_NAME_CHECKED(UGASAttributeSet, Health));
    return FGameplayAttribute(Property);
}
```

#### Data-driven Initialization of Attributes

One way to initialize your attributes is to use a data table. You can create a .csv file in the following format and when importing, select "Attribute Meta Data" as the row type. The name column is a little tricky here: you have to use your class name without the 'U' in front, so MyAttributeSet instead of UMyAttributeSet.

| Name                                                      | BaseValue | MinValue | MaxValue | DerivedAttributeInfo | bCanStack |   |   |   |     |   |     |
| --------------------------------------------------------- | --------- | -------- | -------- | -------------------- | --------- | - | - | - | --- | - | --- |
|                                                           |           | x        |          | y                    |           | z |   |   | ??? |   | T/F |
| MyAttributeSet.Movespeed    300    0    1000        FALSE |           |          |          |                      |           |   |   |   |     |   |     |

| Name                                   | BaseValue | MinValue | MaxValue | DerivedAttributeInfo | bCanStack |
| -------------------------------------- | :-------: | :------: | :------: | :------------------: | :-------: |
| *\[YourAttrClass].\[YourAttrProperty]* |    *x*    |    *y*   |    *z*   |         *???*        |   *T/F*   |
| MyAttributeSet.Movespeed               |    300    |     0    |   1000   |                      |   FALSE   |

Next, add a property in your character to hold a pointer to this table. Make sure to assign your table to this pointer, whether through blueprints or C++:

```cpp
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = Abilities)
UDataTable* AttrDataTable;
```

Somewhere after you create your AbilitySystemComponent, like at the end of BeginPlay(), you can read in the table. It's a simple one-liner:

```cpp
if (AbilitySystem && AttrDataTable) { const UAttributeSet * Attrs = AbilitySystem->InitStats(UMyAttributeSet::StaticClass(), AttrDataTable); }
```

If you setup your table correctly, your stats should be initialized properly!

#### Replication

In the case of a multiplayer game, attributes must usually still be replicated. You replicate them like any other C++ variable, by including the UnrealNetwork.h in your header, adding a "Replicated" tag inside the variable UPROPERTY macro and overriding void GetLifetimeReplicatedProps(TArray& OutLifetimeProps) const so that the variable is properly included as replicated variable.

However, the system requires some extra replication parameters that the normal DOREPLIFETIME macro does not set properly. As such, we need to use a macro which has more parameters, and set these accordingly. It's thankfully quite simple, as all attributes will use the same settings.

```cpp
void UWizardAttributeSet::GetLifetimeReplicatedProps(TArray< FLifetimeProperty > & OutLifetimeProps) const
{
    Super::GetLifetimeReplicatedProps(OutLifetimeProps);

    //DOREPLIFETIME( UMyAttributeSet, MyAttribute); Chances are this is how you would ordinarily do it, however in the case of attributes this'll lead to confusing and annoying replication errors, usually involving clientside ability prediction. 
    DOREPLIFETIME_CONDITION_NOTIFY( UMyAttributeSet, MyAttribute, COND_None, REPNOTIFY_Always); //This is how it is done properly for attributes. }
```

However, attributes need some extra legwork so that values and structs depending on this attribute in question get changed according to a value a client receives from the server. We need to replace the "Replicated"-tag in your UPROPERTY with a "ReplicatedUsing=OnRep\_MyFunction" tag, with OnRep\_MyFunction being the function you wish to call to update your current attribute. Functionally this means each attribute needs its own OnRep function, like so:

```cpp
UPROPERTY(Category = "Attribute", EditAnywhere, ReplicatedUsing = OnRep_MyAttribute, BlueprintReadWrite)
float MyAttribute;

UFUNCTION()
void OnRep_MyAttribute()
{
    GAMEPLAYATTRIBUTE_REPNOTIFY(UMyAttributeSet, MyAttribute);
}
```

### The More Advanced Nitty Gritty

So we have Abilities, Attributes and Effects now. Cool. However, with the tools we have currently introduced, it is difficult to really tie the individual components of this system into each other: Abilities can be called remotely, but only when tags are/have been granted to their owner and without any parameters to work with, GameplayEffects are severely limited by modifiers being so basic and abilities requiring explicit outside triggers to really do anything, and Attributes... well, those are actually working just fine considering they're just float containers at heart, but accessing them and setting up global calculations with them could be easier.

Anyhow, GameplayEvents and GameplayEffectExecutionCalculations are there to really tie up the loose ends of the system together and really make a proper package out of the single excellent systems we have right now.

#### GameplayEffectExectutionCalculation

To put it simply, a **GameplayEffectExecutionCalculation** is a function a GameplayEffect may have and may call in fixed intervals over the effect's duration and/or during initial application. They can do whatever they want really as their Execute function provides them with all parameters necessary to influence their respective actor, ability system or even outside world directly, but due to being a little inconvenient to set up, being C++ only for the moment and lacking any real way to react to the outside world in the way Abilities can, you may be better off with Abilities instead depending on what you want to do.

However, an GameplayEffectExecutionCalculation's unique gimmick is that it can capture attributes from both Source of the GameplayEffect and Target of the GameplayEffect while applying a modifier to them just for this function activation, and use them as parameters of sorts for the calculation, being also able to snapshot particular attributes when the GameplayEffect is first conceived if such a thing would be necessary (for instance, you can attach a GameplayEffectSpec to a fireball projectile, applying it to whoever gets hit, and the fireball naturally shouldn't be influenced by damage boosts and changes on the source once it has initially been fired). This makes GameplayEffectExecutionCalculations amazingly useful for things such as global damage calculations, which will also be our go-to example to understand the setup with in this guide. It will be a very simple and naively implemented example, but it will help you set up a more complex one.

For starters, assume that we have an arbitrary attribute system possessing the following attributes: Health, AttackMultiplier and DefenseMultiplier. Health will decrease as damage is taken (I mean, obviously), AttackMultiplier multiplies outgoing damage with itself and DefenseMultiplier will multiply incoming damage with itself (usually being below 1, or 100%, essentially reducing incoming damage).

I will assume that you will have experimented with the system and the examples in the previous section already and can just add these to your other attributes if you do not already possess similar ones. Just in case, the code of an attribute system with just these values could look a little like this:

```cpp
UCLASS()
class UMyAttributeSet : public UAttributeSet 
{
    GENERATED_BODY()

public:
    //Hitpoints. Self-explanatory.
    UPROPERTY(Category = "Wizard Attributes | Health", EditAnywhere, BlueprintReadWrite)
    FGameplayAttributeData Health;

    //Outgoing damage-multiplier.
    UPROPERTY(Category = "Wizard Attributes | Health", EditAnywhere, BlueprintReadWrite, meta = (HideFromModifiers))
    FGameplayAttributeData AttackMultiplier;

    //Incoming damage-multiplier.
    UPROPERTY(Category = "Wizard Attributes | Health", EditAnywhere, BlueprintReadWrite)
    FGameplayAttributeData DefenseMultiplier;

}
```

However, we actually want to add another attribute on top of that.

Because a GameplayEffectExecutionCalculation takes attributes as pseudo-parameter, we want an extra attribute just so we may define an effect's base damage. We could combine AttackMultiplier and BaseAttackPower into one attribute, but you may get into deep feces once you want to add buffs that influence your outgoing damage, and simply adding values to your BaseAttack may have quite notable balance implications and such if you have a rapid-fire ability that deals a lot of very small damage effects. You COULD change BaseAttack for some buffs and effects, but that's mostly you and your game's call. Basically, having a percentage multiplier on top of a flat attack value is probably a better idea.

Anyhow, you should add BaseAttackPower as an attribute.

```cpp
UCLASS()

class UMyAttributeSet : public UAttributeSet
{
    GENERATED_BODY()
public:
    //Hitpoints. Self-explanatory.
    UPROPERTY(Category = "Wizard Attributes | Health", EditAnywhere, BlueprintReadWrite)
    FGameplayAttributeData Health;

    //Outgoing damage-multiplier.
    UPROPERTY(Category = "Wizard Attributes | Health", EditAnywhere, BlueprintReadWrite, meta = (HideFromModifiers))
    FGameplayAttributeData AttackMultiplier;

    //Incoming damage-multiplier.
    UPROPERTY(Category = "Wizard Attributes | Health", EditAnywhere, BlueprintReadWrite)
    FGameplayAttributeData DefenseMultiplier;

    //Base damage of an outgoing attack.
    UPROPERTY(Category = "Wizard Attributes | Health", EditAnywhere, BlueprintReadWrite)
    FGameplayAttributeData BaseAttackPower;
}
```

Alright, so we got all our important attributes set up, it's time to create a new GameplayEffectExecutionCalculation. Go to your C++ folder in your content explorer, click New C++ class, select GameplayEffectExecutionCalculation as your parent, and select a name for your new class that doesn't take half a decade to pronounce or type. I am calling mine DamageExec. You may do too, if you like.

Once it has finished compiling, you want to change GENERATED\_BODY() at the top of your class declaration in your header to GENERATED\_UCLASS\_BODY(). This way, Unreal's preprocessor-generation-thingie will define us a constructor DamageExec(const FObjectInitializer& ObjectInitializer). We want to implement it in our cpp file like so.

```cpp
UDamageExecution::UDamageExecution(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
{

}
```

We will actually need to do a few things in our constructor, namely giving the Execution info on what attributes we wish to capture from whom. We will need FGameplayEffectAttributeCaptureDefinitions for this. Thankfully, the module has macros for these that makes it easy to set them up.

For the sake of simplicity (as we will need the definitions and UPROPERTYs of our attributes in different functions), we will put these in a struct.

```cpp
struct AttStruct
{
    //The DECLARE_ATTRIBUTE_CAPTUREDEF macro actually only declares two variables. The variable names are dependent on the input, however. Here they will be HealthProperty(which is a UPROPERTY pointer)
    //and HealthDef(which is a FGameplayEffectAttributeCaptureDefinition).
    DECLARE_ATTRIBUTE_CAPTUREDEF(Health);

    DECLARE_ATTRIBUTE_CAPTUREDEF(AttackMultiplier); //Here AttackMultiplierProperty and AttackMultiplierDef. I hope you get the drill.
    DECLARE_ATTRIBUTE_CAPTUREDEF(DefenseMultiplier);
    DECLARE_ATTRIBUTE_CAPTUREDEF(BaseAttackPower);

    AttStruct()
    {
        // We define the values of the variables we declared now. In this example, HealthProperty will point to the Health attribute in the UMyAttributeSet on the receiving target of this execution. The last parameter is a bool, and determines if we snapshot the attribute's value at the time of definition.
        DEFINE_ATTRIBUTE_CAPTUREDEF(UMyAttributeSet, Health, Target, false);

        //This here is a different example: We still take the attribute from UMyAttributeSet, but this time it is BaseAttackPower, and we look at the effect's source for it. We also want to snapshot is because the effect's strength should be determined during its initial creation. A projectile wouldn't change
        //damage values depending on the source's stat changes halfway through flight, after all.
        DEFINE_ATTRIBUTE_CAPTUREDEF(UMyAttributeSet, BaseAttackPower, Source, true);

        //The same rules apply for the multiplier attributes too.
        DEFINE_ATTRIBUTE_CAPTUREDEF(UMyAttributeSet, AttackMultiplier, Source, true);
        DEFINE_ATTRIBUTE_CAPTUREDEF(UMyAttributeSet, DefenseMultiplier, Target, false);
    }
};
```

Now we have a struct that contains the CaptureDefinitions we need, so in the constructor we can simply write:

```cpp
UDamageExec::UDamageExec(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
{
    AttStruct Attributes;

     RelevantAttributesToCapture.Add(Attributes.HealthDef); //RelevantAttributesToCapture is the array that contains all attributes you wish to capture, without exceptions. 
     InvalidScopedModifierAttributes.Add(Attributes.HealthDef); //However, an attribute added here on top of being added in RelevantAttributesToCapture will still be captured, but will not be shown for potential in-function modifiers in the GameplayEffect blueprint, more on that later.

     RelevantAttributesToCapture.Add(Attributes.BaseAttackPowerDef);
     RelevantAttributesToCapture.Add(Attributes.DefenseMultiplierDef);
     RelevantAttributesToCapture.Add(Attributes.AttackMultiplierDef);
}
```

Compile, and voilà, it should now successfully capture attributes. You may check by opening up a GameplayEffect blueprint, and trying to select DamageExec as Execution class. It should allow you to view and select a few more settings. Add a new element in the array CalculationModifiers, and you should see BaseAttackPower, DefenseMultiplier and AttackMultiplier as valid Backing Capture Definition (not Health, however, as you have rendered it as hidden by adding it to `InvalidScopedModifierAttributes`). These are these calculation-only modifiers I talked about. Basically, you can now easily define each gameplay effect's BaseAttackPower individually by adding/setting BaseAttackPower to a value of choice.

Well, but that wouldn't really do anything right now. We have set up capture definitions, but we haven't really set up any functionality. Declare the function `virtual void Execute_Implementation(const FGameplayEffectCustomExecutionParameters& ExecutionParams, OUT FGameplayEffectCustomExecutionOutput& OutExecutionOutput) const override` in your header, and create a fitting definition in your cpp file.

I will just copy-paste an excerpt from Dave's damage calculation from the example project mentioned in this wiki's introduction, and will add comments and changes where appropriate for our level of wisdom and our current setup of attributes.

```cpp
void UDamageExec::Execute_Implementation(const FGameplayEffectCustomExecutionParameters & ExecutionParams, OUT FGameplayEffectCustomExecutionOutput & OutExecutionOutput) const
</pre>
{
    AttStruct Attributes; //Creating the attribute struct, we will need its values later when we want to get the attribute values.

    UAbilitySystemComponent* TargetAbilitySystemComponent = ExecutionParams.GetTargetAbilitySystemComponent(); //We put AbilitySystemComponents into little helper variables. Not necessary, but it helps keeping us from typing so much.

    UAbilitySystemComponent* SourceAbilitySystemComponent = ExecutionParams.GetSourceAbilitySystemComponent();

    AActor* SourceActor = SourceAbilitySystemComponent ? SourceAbilitySystemComponent->AvatarActor : nullptr; //If our AbilitySystemComponents are valid, we get each their owning actors and put them in variables. This is mostly to prevent crashing by trying to get the AvatarActor variable from

    AActor* TargetActor = TargetAbilitySystemComponent ? TargetAbilitySystemComponent->AvatarActor : nullptr; //a null pointer.

    const FGameplayEffectSpec & Spec = ExecutionParams.GetOwningSpec();
    const FGameplayTagContainer* SourceTags = Spec.CapturedSourceTags.GetAggregatedTags();
    const FGameplayTagContainer* TargetTags = Spec.CapturedTargetTags.GetAggregatedTags(); //Some more helper variables: Spec is the spec this execution originated from, and the Source/TargetTags are pointers to the tags granted to source/target actor, respectively.

    FAggregatorEvaluateParameters EvaluationParameters; //We use these tags to set up an FAggregatorEvaluateParameters struct, which we will need to get the values of our captured attributes later in this function.

    EvaluationParameters.SourceTags = SourceTags;
    EvaluationParameters.TargetTags = TargetTags;

    float Health = 0.f;

    //Alright, this is where we get the attribute's captured value into our function. Damage().HealthDef is the definition of the attribute we want to get, we defined EvaluationParameters just above us, and Health is the variable where we will put the captured value into(the Health variable we just declared)
    ExecutionParams.AttemptCalculateCapturedAttributeMagnitude(Attributes.HealthDef, EvaluationParameters, Health); 

    float BaseAttackPower = 0.f;
    ExecutionParams.AttemptCalculateCapturedAttributeMagnitude(Attribute.BaseAttackPowerDef, EvaluationParameters, BaseAttackPower); // We do this for all other attributes, as well.

    float AttackMultiplier = 0.f;
    ExecutionParams.AttemptCalculateCapturedAttributeMagnitude(Attribute.AttackMultiplierDef, EvaluationParameters, AttackMultiplier);

    float DefensePower = 0.f;
    ExecutionParams.AttemptCalculateCapturedAttributeMagnitude(Attribute.DefenseMultiplierPowerDef, EvaluationParameters, DefenseMultiplier);

    //Finally, we go through our simple example damage calculation. BaseAttackPower and AttackMultiplier come from soruce, DefensePower comes from target.
    float DamageDone = BaseAttackPower * AttackMultiplier * DefensePower;

    //An optional step is to clamp to not take health lower than 0. This can be ignored, or implemented in the attribute sets' PostGameplayEffectExecution function. Your call, really.
    DamageDone = FMath::Min<float>( Damage, Health );

    //Finally, we check if we even did any damage in this whole ordeal. If yes, then we will add an outgoing execution modifer to the Health attribute we got from our target, which is a modifier that can still be thrown out by the attribute system if it wishes to throw out the GameplayEffectExecutionCalculation.
    if (DamageDone > 0.f)
    {
        OutExecutionOutput.AddOutputModifier(FGameplayModifierEvaluatedData(Damage().HealthProperty, EGameplayModOp::Additive, -DamageDone));
    }
    //Congratulations, your damage calculation is complete!
}
```

With that, your new damage calculation is now complete. You are free to try to use it through an instant GameplayEffect of choice. Set up a widget or debug string somewhere to tell you your current HP, set the BaseAttackPower of your GameplayEffect's execution to something high like 100, do not forget to assure that the multiplier attributes are not 0, and if your effect reduces your HP, then congrats! You got your very first damage execution calculation running!

You can expand it as you please, as the ExecutionParams parameter of your Execute contains all info about your target, source and GameplayEffectSpec. Want to multiply your damage by your GameplayEffectSpec's level? Easily done. Have an if-statement somewhere that says "if the target actor has tag X that is described to grant him immunity to all damage, reduce the damage of this calculation to 0" if you need such a thing for your game.

It is easy to extend this damage calculation once you get it running initially. Add new multiplier attributes for fire or ice or whatever damage, and have it so that your execution checks for tags on either the source or the EffectSpec itself that say whether to consider these or not. Be creative! You have the tools, you have the power!

An aspect I forgot to mention, and that doesn't quite fit into this example, is that calculations can be used to decide if conditional gameplay effect classes attached to a particular gameplay effect should be applied upon calling of the execution, calling the function MarkConditionalGameplayEffectsToTrigger() from the Execute\_Implementation function's parameter OutExecutionOutput.

For example, you may use calculations to determine if the user's health is below half their maximum health, and call a GameplayEffect granting them a stats buff accordingly. It can be as simple as a simple stat check to as elaborate as a calculation that refuses to apply the conditional GameplayEffect without a certain effect asset tag while applying copies of the owning gameplay effect with this asset tag, simulating an aura-effect that doesn't affect the owner with just a GameplayEffectExecution alone (this example is a little out there, though. Cut me some slack, thinking off a usage example for every other aspect of the system is hard).

Another thing to keep in mind is that executions are not set up to predictively run for a client. As such, their effects will only show themselves to the causing actor when the server receives it.

### Gameplay Events

Alright, this should about be the last major component of the system we haven't extensively talked about. Gameplay Events are amazingly useful due to their ability to trigger abilities without messing around with the ability owner's tags, while at the same time providing the GameplayAbility in question with a useful payload that may contain the source, target actors, magnitude and even generic object pointers for abilities to use as parameter. They're great if you have generic events and situations many abilities will call or listen for. A damage execution may for example throw out a GameplayEvent before damage is applied so that abilities can react with damage-decreasing buffs or pre-damage heals, and one after all multipliers and reductions so that abilities can take the final damage done to, for example, heal the source in proportion to the dealt damage (which would be a simple implementation for lifesteal). Gameplay Events are amazingly flexible, and most kinds of reactionary passive abilities can be implemented with well-implemented Gameplay Events in globally used functions and executions.

You don't really create a new GameplayEvent in the same way you create a new class. They're in fact just mere data structs, and use a tag to tell abilities what kind of event they are. It is up to the abilities themselves to react to them appropriately.

The struct responsible for GameplayEvents, the `FGameplayEventData`, has the following variables:

* **EventTag:** The tag that the event uses as label to be identified by. Do note that an event with tag label X will NOT actually call all GameplayAbilities using this tag as trigger. More on that later.
* **Instigator:** An actor pointer to point to the source or instigator with. Due to the nature of events, you can place any actor reference here, or even leave it null, but it never hurts to put a fitting actor reference here.
* **Target:** Same as instigator, but for targets. Personally, I always set this to the actor we call the gameplay event for, because, I mean, that IS pretty much the target of the GameplayEffect. That said, if you for example have an event that tells a damage source it dealt damage to a target, you can switch it around like that too. It's your call, you are given pretty much no limits or guidelines in this struct.
* **OptionalObject** and **OptionalObject2:** UObject pointers that can be filled with references for extra info. Maybe you want a GameplayEvent in your own child, or maybe a GameplayAbility you inherit all your other spells from that implements at the initial activation, taking the GameplayAbility object itself as parameter.
* **ContextHandle:** GameplayEffectContextHandles are the part of effect specs that store the origin of an effect, such as the ability they came from, the original creation point in the world, the owner of the effect. These all can be useful for the GameplayEvent itself, so add this parameter when you can.
* **InstigatorTags**, **TargetTags:** The tags the instigator and target had during the initial calling of the GameplayEvent. This is different from getting the tags through the instigator/target pointers, as the tag containers through the pointers may update halfway through (obviously, due to being pointers).

These are not actually unused as it turns out, as abilities called with the payload will run these tags through its Source/Target Required/Blocked tags, so if you wish to use these features that are built into every ability by default, you should set the tags accordingly. Also worth noting is that the code doesn't check if any rules are held up though, so it's up to you how you ultimately wish to fill these out. Whether you simply pass the tags currently applied to your target and instigator actors to these containers, whether you opt to fill the containers with tags further describing the situation or a different alternative is all up to you.

* **EventMagnitude:** A singular float. You're more or less free to use it as you want. I personally use it as parameter for my damage events, setting the magnitude to the calculated damage up to the particular step in the calculation (I have an event before all calculations, after bonus multipliers, after resistances, etc.). This is just an example, though.

GameplayEvent structs do not have a constructor that parametrizes these, so you need to set these manually. A little annoying, but you can set up functions to help with that.

Alright, now that we have a GameplayEvent struct, it's time to trigger abilities with it. Abilities may set up a trigger by going to their class defaults and adding a trigger with trigger source Gameplay Event and your tag of choice as values.

We actually can go two different paths to call a GameplayEvent for all abilities in an ability system component:

* We may call the static function `SendGameplayEventToActor(AActor* Actor, FGameplayTag EventTag, FGameplayEventData Payload)` from the `AbilitySystemBlueprintLibrary` class (which is pretty much just one big class of convenience methods exposed to blueprints)
* We may also call the ability system component's `HandleGameplayEvent(FGameplayTag EventTag, const FGameplayEventData* Payload)` function directly.

AbilitySystemBlueprintLibrary's function is safer and more convenient to use, though our actor needs the `IAbilitySystemInterface` implemented for it to work properly. It also does not return the amount of abilities that got triggered by the particular EventTag we use as parameter, though chances are most abilities and systems will very rarely need it. As such, using AbilitySystemBlueprintLibrary's function is often a better idea

Either way, the meaningful parameters of both functions boil down to an FGameplayTag EventTag and the GameplayEvent struct itself, which is usually called Payload. The Payload is self-explanatory, as this is what we will give our ability to work with when called from GameplayEvent. The EventTag is the tag that the ability system component to try to trigger all abilities by. This tag and the tag you give to the struct as label must not be the same thing. For my own usage they usually are, but nothing stops you from having separate tags for event calling and tags for event labelling.

Alright, so if you did everything correctly, your ability should respond to a GameplayEvent of choice (this is easily testable by assigning a random key input on your character to send the event with the event tag of choice to your character, as it should have implemented the interface a long time ago by now).

That's fine and dandy, but where is the payload? Well, going back to the GameplayAbility blueprint for a little, you may or may not have noticed already that there is a different ActivateAbilityEvent defined, but not added to the event graph by default. The event is called ActivateAbilityFromEvent, which does have a Gameplay Event data struct as input.

Your first thought may be to set up a separate chain of blueprint nodes that start from the ActiveAbilityFromEvent node, but this is wrong. The reason for this is not at all simple and in fact rather bizarre, because GameplayAbility's constructor is set in such a way that **it will set a hidden bool to use the struct-less ActivateAbility node for all ability activations when it is present in the blueprint graph of an inherited blueprint class.** I told you man, witchcraft! This module is witchcraft!

Essentially, you will have to replace the `ActivateAbility` node with the Event activation event in your GameplayAbility blueprint. This surrenders your ability to call your ability through conventional means which does not provide the ability with a Gameplay Event struct to work with (such as via action mapping or through TryActivate functions), but you may be okay with this if the ability is meant to be purely passive and response-based.

If you want an ability that does need both gameplay event structs when called via GameplayEvent while still being eligible for manual activations with action mappings/TryActivate, you're best off just splitting active and response-based ability activations into separate abilities that are usually delivered in one bundle.

### Targeting

Way back in the Tasks section we looked at an example task called Wait for Target Data. This task is particularly significant within the AbilitySystem because not only does it provide a system for visualising the targeting of an ability, it provides a framework for the player to send data client->server.

When using this node, the first thing to note is that it is likely best to place before CommitAbility. This is because you can give the player the option to see what their ability is going to do before they choose to activate it. There's a couple of options for Confirmation Type, but the main two are Instant and User Confirmed. These two options are a simple way to swap between quick-casting (Instant), and requiring additional input to confirm and continue the ability. The class option needs to be a child of AGameplayAbilityTargetActor. We'll get to that shortly. We also have some options for a reticle, which I don't use so we won't be covering it, and a filter option. The filter will only really be relevant if you're going to be targeting actors, as opposed to targeting a location or some other thing. A good example might be an AoE spell that affects all targets within a circle - using the filter we can remove the caster from the list of targets, so that we neither highlight them during targeting nor apply effects to them later in the ability.

![Wait Target Data](https://github.com/NickGlenn/Unreal-Engine-4-Community-Guide/tree/58f38c224a525dc8480d25ca361411d9d3e3ff4c/.gitbook/assets/waittargetdata.png)

If you've selected User Confirmed for the Confirmation Type. You'll need to either call `UAbilitySystemComponent::TargetConfirm()` or have Confirm as part of you input binds discussed earlier. You can also call `UAbilitySystemComponent::TargetCancel()` or use Cancel from the input binding if you want to give the player the option to see where they're aiming and then stop the ability from doing anything if they change their mind. This is particularly handy if creating abilities that build or place things in the world. If you're doing user confirmed remember to link the cancelled pin to EndAbility to clean things up!

The data pin on the right of the Task Node will be valid on both the client and the server, and the Valid Data delegate will fire on both. At the back end, this is done in an interesting way since while the task has spawned an Actor (the Targeting Actor), this actor is NOT replicated. So the RPC to send the client data actually goes via the AbilitySystemComponent, which is part of the reason why Targeting Actors are a little peculiar to set up.

#### Target Actors

To create a new Targeting Actor, create a new child inheriting from AGameplayAbilityTargetActor. The two main methods you need to implement are `virtual void StartTargeting(UGameplayAbility* Ability) override` and `virtual void ConfirmTargetingAndContinue() override`.

In StartTargeting, you have the Ability Instance, so sometimes you'll pull in some information about the Ability you're visualising and targeting for from there. An example would be if you have a generic ability for building walls, you might have the type of wall available in the Ability so that the Targeting Actor can find out what mesh it should display. This is also your opportunity to get a ptr to the Avatar that activated the ability, so if anything to do with targeting is dependent on what tags or attributes the Avatar has (maybe the character's AoE size increases based on an attribute) then now is the time to grab that.

ConfirmTargetingAndContinue is where things get weird, but if we distill it down to its most simple, what we want to do is fire the TargetDataReadyDelegate with a payload containing our target data. So if we wanted to send down two transforms containing a source location and a destination, it's going to look something like this:

```cpp
FGameplayAbilityTargetData_LocationInfo *ReturnData = new FGameplayAbilityTargetData_LocationInfo();
ReturnData->SourceLocation.LocationType = EGameplayAbilityTargetingLocationType::LiteralTransform;
ReturnData- >SourceLocation.LiteralTransform = FTransform(SourceLocation);
ReturnData- >TargetLocation.LocationType = EGameplayAbilityTargetingLocationType::LiteralTransform;
ReturnData- >TargetLocation.LiteralTransform = FTransform((TargetLocation - SourceLocation).ToOrientationQuat(), TargetLocation);
FGameplayAbilityTargetDataHandle Handle(ReturnData);
TargetDataReadyDelegate.Broadcast(Handle);
```

The key struct is `FGameplayAbilityTargetData`, which `FGameplayAbilityTargetData_LocationInfo` and other variants inherit from. So if you want to send a location or two, use `FGameplayAbilityTargetData_LocationInfo`, if you want to send some actors, use `FGameplayAbilityTargetData_ActorArray`, if you want to send a hitresult, use `FGameplayAbilityTargetData_SingleTargetHit`. These cover most common use cases, but let's assume you're a special snowflake and you want to send some other piece of data that isn't covered. Remember, this is your method for pushing data client->server for ability activation, and as such it can be tampered with by cheaters, so be really careful with what you send and what you do with it. I (/u/woppin) use this for sending a float that states how long the button has been held for. The server also has this value, but it's not exact, so it's checked against the player's ping and the value the player sent to make sure it's reasonable. You have been warned.

OK, so you still want to send some more info client->server and you understand the risks. In this example we're going to send a source and destination location, plus a float and an int. In the actual project, this is used to let the player click and drag to draw a line (source and destination) that becomes a wall, with the time the button is held (float) increasing the strength of the wall. First thing to do is to create a struct that inherits from `FGameplayAbilityTargetData`:

```cpp
USTRUCT(BlueprintType)
struct FGameplayAbilityCastingTargetingLocationInfo : public FGameplayAbilityTargetData
{
    GENERATED_USTRUCT_BODY()

    /** Amount of time the ability has been charged */
    UPROPERTY(BlueprintReadWrite, EditAnywhere, Category = Targeting)
    float ChargeTime;

    /** The ID of the Ability that is performing targeting */
    UPROPERTY()
    uint32 UniqueID;

    /** Generic location data for source */
    UPROPERTY(BlueprintReadWrite, EditAnywhere, Category = Targeting)
    FGameplayAbilityTargetingLocationInfo SourceLocation;

    /** Generic location data for target */
    UPROPERTY(BlueprintReadWrite, EditAnywhere, Category = Targeting)
    FGameplayAbilityTargetingLocationInfo TargetLocation;

    // -------------------------------------
    virtual bool HasOrigin() const override
    {
        return true;
    }

    virtual FTransform GetOrigin() const override
    {
        return SourceLocation.GetTargetingTransform();
    }

    // -------------------------------------
    virtual bool HasEndPoint() const override
    {
        return true;
    }

    virtual FVector GetEndPoint() const override
    {
        return TargetLocation.GetTargetingTransform().GetLocation();
    }

    virtual FTransform GetEndPointTransform() const override
    {
        return TargetLocation.GetTargetingTransform();
    }

    // -------------------------------------
    virtual UScriptStruct* GetScriptStruct() const override
    {
        return FGameplayAbilityCastingTargetingLocationInfo::StaticStruct();
    }

    virtual FString ToString() const override
    {
        return TEXT("FGameplayAbilityCastingTargetingLocationInfo");
    }

    bool NetSerialize(FArchive&amp; Ar, class UPackageMap* Map, bool&amp; bOutSuccess);
};

template<>
struct TStructOpsTypeTraits<FGameplayAbilityCastingTargetingLocationInfo> : public TStructOpsTypeTraitsBase2<FGameplayAbilityCastingTargetingLocationInfo>
{
    enum
    {
        WithNetSerializer = true    // For now this is REQUIRED for FGameplayAbilityTargetDataHandle net serialization to work
    };
};
```

I have no idea what that last part does! In our .cpp we need to add an implementation for NetSerialize to include our new data (a float and an int):

```cpp
bool FGameplayAbilityCastingTargetingLocationInfo::NetSerialize(FArchive& Ar, class UPackageMap* Map, bool& bOutSuccess)
{
    SourceLocation.NetSerialize(Ar, Map, bOutSuccess);
    TargetLocation.NetSerialize(Ar, Map, bOutSuccess);
    Ar << ChargeTime;
    Ar << UniqueID;
    bOutSuccess = true;
    return true;
}
```

Now we update our targeting confirmation to include new data:

```cpp
FGameplayAbilityCastingTargetingLocationInfo *ReturnData = new FGameplayAbilityCastingTargetingLocationInfo();
ReturnData->ChargeTime = CastingCharacter- >GetChargeTime(); // Get the wall strength
ReturnData->UniqueID = OwningAbility- >GetUniqueID(); // Ignore this
FVector SourceLocation = CastingCharacter->GetCastingSourceLocation(); // Get where the character is aiming from
FVector TargetLocation = CastingCharacter->GetCastingTargetLocation(); // Get where the character is aiming to
ClampLocations(SourceLocation, TargetLocation); // Limit the maximum wall length

// Set Location Data
ReturnData->SourceLocation.LocationType = EGameplayAbilityTargetingLocationType::LiteralTransform;
ReturnData->SourceLocation.LiteralTransform = FTransform(SourceLocation);
ReturnData->TargetLocation.LocationType = EGameplayAbilityTargetingLocationType::LiteralTransform;
ReturnData->TargetLocation.LiteralTransform = FTransform((TargetLocation - SourceLocation).ToOrientationQuat(), TargetLocation);
FGameplayAbilityTargetDataHandle Handle(ReturnData);
TargetDataReadyDelegate.Broadcast(Handle);
```

The last remaining pieces worth mentioning are firstly that you can visualise the ability in the actor as well, but how you do that is entirely up to you, and secondly you might want to re-use the targeting actor if you're rapidly re-firing the same ability over and over. Also note that if the ability is instant, the actor will spawn and then immediately be destroyed, so visualisation is a bit pointless. For visualisation generally follow the model of spawning the meshes/particles you need in StartTargeting, and then use tick to update each frame based on changes in player input. This will probably mean storing where you're aiming in the PlayerController or the Character's Tick, storing a ptr to one of those two in StartTargeting, and then Calling out to them during the TargetingActor's Tick. Of course you don't have to use tick if you're not doing analogue targeting (eg. targeting controlled by keys instead of mouse) or if you can handle a lower refresh rate and use a Timer instead.

There's quite a few examples of TargetingActors already in the Plugin, so look at them if in doubt.

## Conclusion

That's it! You now have a somewhat complete overview of the module's core systems, as well as their helper systems that allow better interaction between each of them.

Questions, and typo-searching would be appreciated. As would be complementing sections of this guide with knowledge and discoveries of your own should you garner enough experience to contribute, as while I feel like I have a rough overview of the module down, a lot of the fine lines of this system are still lost on me.

Once again, this guide is taken from [a post on the forums](https://forums.unrealengine.com/showthread.php?137352-GameplayAbilities-and-you) by [KZJ](https://forums.unrealengine.com/member.php?267563-KZJ), and was originally adapted for the Unreal Engine wiki by Jay2645.

## Common Issues

#### Cues not visible in packaged game

By default, only referenced assets are included in packaged builds, and if you've set up your GameplayCues to be triggered by tags this won't be enough. GameplayCues usually inherit from one of two base classes, so they can be added to the Asset Manager like so:

![Cue Packaging](https://github.com/NickGlenn/Unreal-Engine-4-Community-Guide/tree/58f38c224a525dc8480d25ca361411d9d3e3ff4c/.gitbook/assets/cuepackaging.png)


# DevOps


# Linking DLLs

This wiki article was written by Original Author ZkarmaKun (talk); Updated & Improved by F3NR1S (talk), XenoEgger, Darkgaze; Converted by jfaw

## Overview

This tutorial explains how to link / bind your own [DLL](https://en.wikipedia.org/wiki/Dynamic-link_library) to Unreal Engine 4 and how to use your DLL's methods for visual scripting in a [Blueprint Function Library](https://docs.unrealengine.com/latest/INT/Programming/BlueprintFunctionLibraries/).

## Creating a C++ DLL

This article originally centered on binding the DLL but here is also a brief explanation on how to build DLLs in different [IDEs](https://en.wikipedia.org/wiki/Integrated_development_environment).

### Visual Studio Community 2015

* Create a new project: *menu bar -> File -> New -> Project...*
  1. In the New Project window on the left select *Installed -> Templates -> Visual C++ -> Win32.*
  2. Select *Win32 Project* in the middle.
  3. Name: the project *CreateAndLinkDLLTut* and the Solution name: *CreateAndLinkDLLTutSol*.
  4. Click *OK*.&#x20;
* In the next window *Win32 Application Wizard - CreateAndLinkDLLTut* click *Next*.
  1. In the **Application Settings** select
     * *Application type: -> DLL*
     * *Additional options: -> Empty project*
  2. Click *Finish*.&#x20;
* On the left side of Visual Studio in the Solution Explorer make sure that CreateAndLinkDLLTut is selected.
  1. Click *main menu -> Project -> Add Class...*
  2. In the *Add Class* window select *Installed -> Visual C++ -> C++ ->* on the left side and *C++ Class* in the middle then click *Add*.
  3. In the *Generic C++ Class Wizard* window fill in *CreateAndLinkDLLfile* into the *Class name: input* field. Click *Finish*.
* On the left side in the *Solution Explorer* select the file *CreateAndLinkDLLfile.h* and copy & paste the following code. Replace all automatically generated code.

```cpp
#pragma once  

#define DLL_EXPORT __declspec(dllexport)    //shortens __declspec(dllexport) to DLL_EXPORT

#ifdef __cplusplus        //if C++ is used convert it to C to prevent C++'s name mangling of method names
extern "C"
{
#endif

    bool DLL_EXPORT getInvertedBool(bool boolState);
    int DLL_EXPORT getIntPlusPlus(int lastInt);
    float DLL_EXPORT getCircleArea(float radius);
    char DLL_EXPORT *getCharArray(char* parameterText);
    float DLL_EXPORT *getVector4( float x, float y, float z, float w);

#ifdef __cplusplus
}
#endif
```

* Then select the file *CreateAndLinkDLLfile.cpp* and copy & paste the following code. Replace all automatically generated code.

```cpp
#pragma once

#include "string.h"
#include "CreateAndLinkDLLFile.h"


//Exported method that invertes a given boolean.
bool getInvertedBool(bool boolState)
{
    return bool(!boolState);
}

//Exported method that iterates a given int value.
int getIntPlusPlus(int lastInt)
{
    return int(++lastInt);
}

//Exported method that calculates the are of a circle by a given radius.
float getCircleArea(float radius)
{
    return float(3.1416f * (radius * radius));
}

//Exported method that adds a parameter text to an additional text and returns them combined.
char *getCharArray(char* parameterText)
{
    char* additionalText = " world!";

    if (strlen(parameterText) + strlen(additionalText) + 1 > 256)
    {
        return "Error: Maximum size of the char array is 256 chars.";
    }

    char combinedText[256] = "";

    strcpy_s( combinedText, 256, parameterText);
    strcat_s( combinedText, 256, additionalText);

    return ( char* )combinedText;
}

//Exported method that adds a vector4 to a given vector4 and returns the sum.
float *getVector4( float x, float y, float z, float w )
{
    float* modifiedVector4 = new float[4];

    modifiedVector4[0] = x + 1.0F;
    modifiedVector4[1] = y + 2.0F;
    modifiedVector4[2] = z + 3.0F;
    modifiedVector4[3] = w + 4.0F;

    return ( float* )modifiedVector4;
}
```

* Save with *menu bar -> File -> Save All*.
* Set the proper build options for your 64-bit DLL: In the menu bar select **Release** as *Solution Configuration* and **x64** as *Solution Platform*. ( If you use a 32-bit Windows system please select **x86** instead of x64. )
* Build the DLL with *menu bar -> Build -> Build CreateAndLinkDLLTut*. The Output at the bottom should show a message like *========== Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped ==========*.
* The 64-bit DLL was created in the folder *.../CreateAndLinkDLLTutSol/x64/Release/* and is called *CreateAndLinkDLLTut.dll*. ( The 32-bit DLL was created in the folder *.../CreateAndLinkDLLTutSol/Release/* and is called *CreateAndLinkDLLTut.dll*. [You won't be able to bind the DLL if the platforms are different.](https://answers.unrealengine.com/questions/30927/does-it-make-a-difference-if-you-load-a-custom-win.html) )

## Unreal Engine Project

* On **Unreal Engine**, create a new project: *New Project -> C++ -> Basic Code*.
* Name the project *CreateAndLinkDLLProj* and create it.
* Open **Windows Explorer**.
  1. Go to the main folder of your created UE4 project.
  2. Add a folder called [Plugins](https://docs.unrealengine.com/latest/INT/Programming/Plugins/index.html#pluginfolders).
  3. In the Plugins folder create an other folder called *MyTutorialDLLs*.
  4. Copy and paste the DLL *CreateAndLinkDLLTut.dll* you have created earlier into the folder *MyTutorialDLLs*.&#x20;
* Add a new C++ class to your project in **Unreal Editor**.
* Choose the *Blueprint Function Library* as the base class.
* Name your blueprint function library *CreateAndLinkDLLTutBFL*.
* If **Visual Studio** does not open it automatically, open it by double clicking *CreateAndLinkDLLTutBFL* in the UE4 content browser.
* Open the *CreateAndLinkDLLTutBFL.h* and *CreateAndLinkDLLTutBFL.cpp* files.
* Select the file *CreateAndLinkDLLTutBFL.h* and copy & paste the following code:

```cpp
#pragma once

#include "Kismet/BlueprintFunctionLibrary.h"
#include "CreateAndLinkDLLTutBFL.generated.h"


UCLASS()
class CREATEANDLINKDLLPROJ_API UCreateAndLinkDLLTutBFL : public UBlueprintFunctionLibrary
{
    GENERATED_BODY()

public:

    UFUNCTION(BlueprintCallable, Category = "My DLL Library")
    static bool importDLL( FString folder, FString name);


    UFUNCTION(BlueprintCallable, Category = "My DLL Library")
    static bool importMethodGetInvertedBool( );

    UFUNCTION(BlueprintCallable, Category = "My DLL Library")
    static bool importMethodGetIntPlusPlus( );

    UFUNCTION(BlueprintCallable, Category = "My DLL Library")
    static bool importMethodGetCircleArea( );

    UFUNCTION(BlueprintCallable, Category = "My DLL Library")
    static bool importMethodGetCharArray( );

    UFUNCTION( BlueprintCallable, Category = "My DLL Library" )
    static bool importMethodGetVector4( );


    UFUNCTION(BlueprintCallable, Category = "My DLL Library")
    static bool getInvertedBoolFromDll(bool boolState);

    UFUNCTION(BlueprintCallable, Category = "My DLL Library")
    static int getIntPlusPlusFromDll(int lastInt);

    UFUNCTION(BlueprintCallable, Category = "My DLL Library")
    static float getCircleAreaFromDll(float radius);

    UFUNCTION(BlueprintCallable, Category = "My DLL Library")
    static FString getCharArrayFromDll(FString parameterText);

    UFUNCTION( BlueprintCallable, Category = "My DLL Library" )
    static FVector4 getVector4FromDll( FVector4 vector4 );


    UFUNCTION(BlueprintCallable, Category = "My DLL Library")
    static void freeDLL();
};
```

* Select the file *CreateAndLinkDLLTutBFL.cpp* and copy & paste the following code:

```cpp
#include "CreateAndLinkDLLProj.h"
#include "CreateAndLinkDLLTutBFL.h"

typedef bool(*_getInvertedBool)(bool boolState); // Declare a method to store the DLL method getInvertedBool.
typedef int(*_getIntPlusPlus)(int lastInt); // Declare a method to store the DLL method getIntPlusPlus.
typedef float(*_getCircleArea)(float radius); // Declare a method to store the DLL method getCircleArea.
typedef char*(*_getCharArray)(char* parameterText); // Declare a method to store the DLL method getCharArray.
typedef float*(*_getVector4)(float x, float y, float z, float w); // Declare a method to store the DLL method getVector4.

_getInvertedBool m_getInvertedBoolFromDll;
_getIntPlusPlus m_getIntPlusPlusFromDll;
_getCircleArea m_getCircleAreaFromDll;
_getCharArray m_getCharArrayFromDll;
_getVector4 m_getVector4FromDll;

void *v_dllHandle;


#pragma region Load DLL

// Method to import a DLL.
bool UCreateAndLinkDLLTutBFL::importDLL(FString folder, FString name)
{
    FString filePath = *FPaths::GamePluginsDir() + folder + "/" + name;

    if (FPaths::FileExists(filePath))
    {
        v_dllHandle = FPlatformProcess::GetDllHandle(*filePath); // Retrieve the DLL.
        if (v_dllHandle != NULL)
        {
            return true;
        }
    }
    return false;    // Return an error.
}
#pragma endregion Load DLL

#pragma region Import Methods

// Imports the method getInvertedBool from the DLL.
bool UCreateAndLinkDLLTutBFL::importMethodGetInvertedBool()
{
    if (v_dllHandle != NULL)
    {
        m_getInvertedBoolFromDll = NULL;
        FString procName = "getInvertedBool";    // Needs to be the exact name of the DLL method.
        m_getInvertedBoolFromDll = (_getInvertedBool)FPlatformProcess::GetDllExport(v_dllHandle, *procName);
        if (m_getInvertedBoolFromDll != NULL)
        {
            return true;
        }
    }
    return false;    // Return an error.
}

// Imports the method getIntPlusPlus from the DLL.
bool UCreateAndLinkDLLTutBFL::importMethodGetIntPlusPlus()
{
    if (v_dllHandle != NULL)
    {
        m_getIntPlusPlusFromDll = NULL;
        FString procName = "getIntPlusPlus";    // Needs to be the exact name of the DLL method.
        m_getIntPlusPlusFromDll = (_getIntPlusPlus)FPlatformProcess::GetDllExport(v_dllHandle, *procName);
        if (m_getIntPlusPlusFromDll != NULL)
        {
            return true;
        }
    }
    return false;    // Return an error.
}

// Imports the method getCircleArea from the DLL.
bool UCreateAndLinkDLLTutBFL::importMethodGetCircleArea()
{
    if (v_dllHandle != NULL)
    {
        m_getCircleAreaFromDll = NULL;
        FString procName = "getCircleArea";    // Needs to be the exact name of the DLL method.
        m_getCircleAreaFromDll = (_getCircleArea)FPlatformProcess::GetDllExport(v_dllHandle, *procName);
        if (m_getCircleAreaFromDll != NULL)
        {
            return true;
        }
    }
    return false;    // Return an error.
}

// Imports the method getCharArray from the DLL.
bool UCreateAndLinkDLLTutBFL::importMethodGetCharArray()
{
    if (v_dllHandle != NULL)
    {
        m_getCharArrayFromDll = NULL;
        FString procName = "getCharArray";    // Needs to be the exact name of the DLL method.
        m_getCharArrayFromDll = (_getCharArray)FPlatformProcess::GetDllExport(v_dllHandle, *procName);
        if (m_getCharArrayFromDll != NULL)
        {
            return true;
        }
    }
    return false;    // Return an error.
}

// Imports the method getVector4 from the DLL.
bool UCreateAndLinkDLLTutBFL::importMethodGetVector4( )
{
    if( v_dllHandle != NULL )
    {
        m_getVector4FromDll = NULL;
        FString procName = "getVector4";    // Needs to be the exact name of the DLL method.
        m_getVector4FromDll = ( _getVector4 ) FPlatformProcess::GetDllExport( v_dllHandle, *procName );
        if( m_getVector4FromDll != NULL )
        {
            return true;
        }
    }
    return false;    // Return an error.
}

#pragma endregion Import Methods

#pragma region Method Calls

// Calls the method getInvertedBoolFromDll that was imported from the DLL.
bool UCreateAndLinkDLLTutBFL::getInvertedBoolFromDll(bool boolState)
{
    if (m_getInvertedBoolFromDll != NULL)
    {
        bool out = bool(m_getInvertedBoolFromDll(boolState)); // Call the DLL method with arguments corresponding to the exact signature and return type of the method.
        return out;
    }
    return boolState;    // Return an error.
}

// Calls the method m_getIntPlusPlusFromDll that was imported from the DLL.
int UCreateAndLinkDLLTutBFL::getIntPlusPlusFromDll(int lastInt)
{
    if (m_getIntPlusPlusFromDll != NULL)
    {
        int out = int(m_getIntPlusPlusFromDll(lastInt)); // Call the DLL method with arguments corresponding to the exact signature and return type of the method.
        return out;
    }
    return -32202;    // Return an error.
}

// Calls the method m_getCircleAreaFromDll that was imported from the DLL.
float UCreateAndLinkDLLTutBFL::getCircleAreaFromDll(float radius)
{
    if (m_getCircleAreaFromDll != NULL)
    {
        float out = float(m_getCircleAreaFromDll(radius)); // Call the DLL method with arguments corresponding to the exact signature and return type of the method.
        return out;
    }
    return -32202.0F;    // Return an error.
}

// Calls the method m_getCharArrayFromDLL that was imported from the DLL.
FString UCreateAndLinkDLLTutBFL::getCharArrayFromDll(FString parameterText)
{
    if (m_getCharArrayFromDll != NULL)
    {
        char* parameterChar = TCHAR_TO_ANSI(*parameterText);

        char* returnChar = m_getCharArrayFromDll(parameterChar);

        return (ANSI_TO_TCHAR(returnChar));
    }
    return "Error: Method getCharArray was probabey not imported yet!";    // Return an error.
}

// Calls the method m_getVector4FromDll that was imported from the DLL.
FVector4 UCreateAndLinkDLLTutBFL::getVector4FromDll( FVector4 vector4 )
{
    if( m_getVector4FromDll != NULL )
    {
        float* vector4Array = m_getVector4FromDll( vector4.X, vector4.Y, vector4.Z, vector4.W );

        return FVector4( vector4Array[0], vector4Array[1], vector4Array[2], vector4Array[3] );
    }
    return FVector4( -32202.0F, -32202.0F, -32202.0F, -32202.0F );    // Return an error.
}
#pragma endregion Method Calls


#pragma region Unload DLL

// If you love something  set it free.
void UCreateAndLinkDLLTutBFL::freeDLL()
{
    if (v_dllHandle != NULL)
    {
        m_getInvertedBoolFromDll = NULL;
        m_getIntPlusPlusFromDll = NULL;
        m_getCircleAreaFromDll = NULL;
        m_getCharArrayFromDll = NULL;
        m_getVector4FromDll = NULL;

        FPlatformProcess::FreeDllHandle(v_dllHandle);
        v_dllHandle = NULL;
    }
}
#pragma endregion Unload DLL
```

* Save with *menu bar -> File -> Save All*.

## Creating the Blueprint

* First hit the Compile button PD CompileButton.PNG of the Unreal Editor to compile the code you've added and saved in Visual Studio before.
* In Unreal Editor add a new Blueprint Class called *BP\_DllTest* and open it. ([How to create a blueprint class](https://docs.unrealengine.com/latest/INT/Engine/Blueprints/UserGuide/Types/ClassBlueprint/Creation/index.html))
* Select the *Event Graph* and add the following nodes construct ( Click it and click it again to download it! ).&#x20;
  * **Important note**: If you don't see the functions in the dropdown, try compiling from Visual Studio and then reopening UE4. If this doesn't work, close UE4, remove Binaries folder and Intermediate folder (but avoid deleting Intermediate/Project Files). You will be prompted to rebuild the project.

![Project Creation](https://3425263208-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M3mx7Lszp8LdwKKD7yR%2F-M462J1RJdKu8dvwBJxs%2F-M462LJrNMXkTkd6Ynoa%2Fblueprint-graph1.png?generation=1586035001296251\&alt=media)

* Then compile and save the blueprint and drag & drop it into the level.
* The result should look like this:

![Project Creation](https://3425263208-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M3mx7Lszp8LdwKKD7yR%2F-M462J1RJdKu8dvwBJxs%2F-M462LJtYXOAZAmd5Lby%2Fresult1.png?generation=1586035000084745\&alt=media)

## Project Source Code

You can download the final [Visual Studio Solution of the DLL](https://github.com/XenoEgger/CreateAndLinkDLLTutSol) and the [Unreal Engine 4 project](https://github.com/XenoEgger/CreateAndLinkDLLProj) from GitHub. ( You may need to rebuild the DLL and copy it to your UE4 *Plugins* folder. )

## Final Words

* You can use any DLL from C code or C++ or other languages.
* You can use unmanaged or managed (CLR, .Net Framework) code from a project in your solution or external.
* Most issues arise from differences in the signature of the DLL function and the type definition in the Unreal Project.
* Automatic packaging of third party DLL is not yet supported, you will need to package the DLL, the DLL folder and the plugin folder as well, which is not created in a package by default at this time.
* Be mindful of load times of DLL, it may slow down your project.
* Be mindful of processing time of your DLL, your project loses execution control inside the DLL, until it returns, it may be expensive to perform some operations.
* To go further with this tutorial:
  * C++ with proper class, namespace and name mangling.
  * DLL with multithreading and callback example.


# AR & VR

Augmented Reality & Virtual Reality


# Integrating OpenCV into Unreal Engine 4

This article was originally written by Ginku; Converted by jfaw

## Overview

Hello all! This is my first wiki tutorial, I hope it can be of help to someone!

I am making this tutorial in response to a few requests. This will be a detailed, step-by-step guide to linking OpenCV 3.2 to Unreal Engine 4 using the Unreal Build Tool. You can find a general tutorial on linking any static library to Unreal [here](https://github.com/NickGlenn/Unreal-Engine-4-Community-Guide/tree/1c9f59fcc997508eb51f94b2d1e18c3544296406/wiki-archives/ar-vr/Linking_Static_Libraries_Using_The_Build_System/README.md). I recommend reading it in addition to this tutorial, as it is what this tutorial is based on.

This tutorial focuses on the windows OS for simplicity. Note that the same process works for other OS, but you might need to build OpenCV from source.

### Why OpenCV?

OpenCV is a powerful open-source computer vision library, and once included into any unreal engine 4 project it will allow for the use of the engine in many non-traditional ways. Including OpenCV in a project as a dependency will allow developers to create state-of-the-art environments with either augmented reality components, virtual reality environments that resemble the user’s surroundings, or any mixture of the two. In this tutorial I will show you how to quickly and painlessly include OpenCV in any unreal engine 4 project with the Windows OS, and then I will guide you through displaying a webcam in a level.

### Using the Plugin

I have created a plugin that does all the OpenCV library linking, which can be found on its github. Installation instructions are inside the README file. With this plugin, you can skip to the Moving to Blueprints section of this tutorial. If you do so, be sure to enable the Computer Vision > OpenCV plugin inside the editor's Edit > Plugins menu.

Note: after installation, be sure to regenerate project files. For visual studios, right click your project (.uasset) file and select 'generate visual studio project files' after deleting your previous visual studios file.

## Linking OpenCV in Visual Studios

Before you continue, make sure you are starting from a code project, or have added code to your project with the editor!

### Copying the OpenCV Files

In order to begin, all of OpenCV’s include and library files will need to be added to your project’s `/ThirdParty` directory. To begin, install **OpenCV 3.2** or locate your installation of OpenCV 3.2 and do the following:

* Inside the OpenCV install directory you will find the `/build/include` directory. Copy all of the contents of this directory into the `[ProjectRootDirectory]/ThirdParty/OpenCV/Includes` directory.
* Next, copy the *opencv\_world320.dll* and *opencv\_ffmpeg320\_64.dll* files in the `/build/x64/vc14/bin` folder and the 'opencv\_world320.lib', files in the `/build/x64/vc14/lib` folder to the `[ProjectRootDirectory]/ThirdParty/OpenCV/Libraries/Win64/` directory.

*Note:* This process is similar for any version of OpenCV or any third party library. You only need the runtime libraries (not the debug ones with a 'd' appended, such as *opencv\_world320d.dll* unless you need the debug versions).

### Adding OpenCV Dependencies

Locate and open your projects module rules file, which should be in your projects `Source/[Project Name]` directory. (It will be in the format of *ProjectName.Build.cs*) In this file, we will add the necessary code so that the unreal build tool will include all of the necessary dependencies during build time.

First, be sure to add the following include at the top of the file:

```csharp
using System.IO;
```

This lets you use the Path helper class, which is very useful for assembling directory paths!

Inside your ModuleRules class and before the constructor, add the following getter:

```csharp
private string ThirdPartyPath
{ 
    get { return Path.GetFullPath(Path.Combine(ModuleDirectory, "../../ThirdParty/")); } 
}
```

This is a helpful little function for retrieving the `/ThirdParty/` path, and can be very convenient when including more than one third party dependency to a project. Now, add the following function after the constructor:

```csharp
public bool LoadOpenCV(TargetInfo Target)
{
    // Start OpenCV linking here!
    bool isLibrarySupported = false;

    // Create OpenCV Path 
    string OpenCVPath = Path.Combine(ThirdPartyPath, "OpenCV");

    // Get Library Path 
    string LibPath = "";
    bool isdebug = Target.Configuration == UnrealTargetConfiguration.Debug && BuildConfiguration.bDebugBuildsActuallyUseDebugCRT;
    if (Target.Platform == UnrealTargetPlatform.Win64)
    {
        LibPath = Path.Combine(OpenCVPath, "Libraries", "Win64");
        isLibrarySupported = true;
    }
    else
    {
        string Err = string.Format("{0} dedicated server is made to depend on {1}. We want to avoid this, please correct module dependencies.", Target.Platform.ToString(), this.ToString()); System.Console.WriteLine(Err);
    }

    if (isLibrarySupported)
    {
        //Add Include path 
        PublicIncludePaths.AddRange(new string[] { Path.Combine(OpenCVPath, "Includes") });

        // Add Library Path 
        PublicLibraryPaths.Add(LibPath);

        //Add Static Libraries
        PublicAdditionalLibraries.Add("opencv_world320.lib");

        //Add Dynamic Libraries
        PublicDelayLoadDLLs.Add("opencv_world320.dll");
        PublicDelayLoadDLLs.Add("opencv_ffmpeg320_64.dll");
    }

    Definitions.Add(string.Format("WITH_OPENCV_BINDING={0}", isLibrarySupported ? 1 : 0));

    return isLibrarySupported;
}
```

This function includes all of the required includes and libraries for OpenCV. Now, simply call this function inside your project constructor after the standard public modules:

```csharp
PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore", "RHI", "RenderCore", "ShaderCore" });

LoadOpenCV(Target);
```

Be sure to add the **InputCore**, **RHI**, and **RenderCore** engine modules to the *public* dependency list, we will use these later to create a dynamic texture from the camera feed. The *PrivateIncludePaths* will allow you to include the OpenCV header files without full paths.

Now, your project should successfully compile with OpenCV included within the engine build! However, there is one more thing that needs to be included before you can launch an instance of your project’s editor.

### Copying the DLL's to the Build

Before your project will run with any OpenCV code, you will first need to add all of the dynamically linked library (*.dll*) files that you use to your editor’s bin folder. Your editor will typically be a 64-bit application, so copy all of the *.dll* files (*opencv\_world320.dll* and *opencv\_ffmpeg320\_64.dll*) from the OpenCV’s 64 bit bin folder (full directory shown above) and paste them inside the `[ProjectRootDirectory]/Binaries/Win64` directory.

Note: These DLL's should also be included with any distributions of the project (such as when packaging your game/project), by including them in the same directory as the project's executable (`MY_PROJECT.exe`).

### Fixing Library Collisions

There is a collision between the OpenCV3 library and UE4. To fix this, **comment out lines \~51 to \~55 and line \~852** of the *utility.hpp* header file in the `'[ProjectRootDirectory]\ThirdParty\OpenCV\Includes\opencv2\core` directory.

```cpp
// NOTE: The OpenCV 'check' function has been commented out, as it conflicts with UE4 check - see line ~852
//#if defined(check)
//#  warning Detected Apple 'check' macro definition, it can cause build conflicts. Please, include this header before any Apple headers.
//#endif

...

//bool check() const;
```

## Adding a WebcamReader Class

You are now ready to launch an instance of your editor and start using OpenCV! Right click the project name in your solution explorer, and select *Debug > Start new instance*. If you get an error about the os being unable to load your dll, check out the discussion page. Once the editor loads, select *File > New C++ Class…* and select the `Actor` parent class. Press Next, name the actor `WebcamReader` and press *Create Class*. Once Unreal has finished adding the new actor, the new header and source files will be opened inside Visual Studios.

Add the following code to each of them:

#### Header

```cpp
// A simple webcam reader using the OpenCV library
// Author: The UE4 community

#pragma once

#include "opencv2/core.hpp"
#include "opencv2/highgui.hpp"    
#include "opencv2/imgproc.hpp"
#include "opencv2/videoio.hpp"
#include "GameFramework/Actor.h"
#include "Runtime/Engine/Classes/Engine/Texture2D.h"
#include "WebcamReader.generated.h"

UCLASS()
class YOURPROJECT_API AWebcamReader : public AActor
{
    GENERATED_BODY()

public:    
    // Sets default values for this actor's properties
    AWebcamReader();

    // Called when the game starts or when spawned
    virtual void BeginPlay() override;

    // Called every frame
    virtual void Tick( float DeltaSeconds ) override;

    // The device ID opened by the Video Stream
    UPROPERTY(BlueprintReadWrite, EditAnywhere, Category = Webcam)
    int32 CameraID;

    // If the webcam images should be resized every frame
    UPROPERTY(BlueprintReadWrite, EditAnywhere, Category = Webcam)
    bool ShouldResize;

    // The targeted resize width and height (width, height)
    UPROPERTY(BlueprintReadWrite, EditAnywhere, Category = Webcam)
    FVector2D ResizeDeminsions;

    // The rate at which the color data array and video texture is updated (in frames per second)
    UPROPERTY(BlueprintReadWrite, EditAnywhere, Category = Webcam)
    float RefreshRate;

    // The refresh timer
    UPROPERTY(BlueprintReadWrite, Category = Webcam)
    float RefreshTimer;

    // Blueprint Event called every time the video frame is updated
    UFUNCTION(BlueprintImplementableEvent, Category = Webcam)
    void OnNextVideoFrame();

    // OpenCV fields
    cv::Mat frame;
    cv::VideoCapture stream;
    cv::Size size;

    // OpenCV prototypes
    void UpdateFrame();
    void DoProcessing();
    void UpdateTexture();

    // If the stream has succesfully opened yet
    UPROPERTY(BlueprintReadOnly, Category = Webcam)
    bool isStreamOpen;

    // The videos width and height (width, height)
    UPROPERTY(BlueprintReadWrite, Category = Webcam)
    FVector2D VideoSize;

    // The current video frame's corresponding texture
    UPROPERTY(BlueprintReadOnly, Category = Webcam)
    UTexture2D* VideoTexture;

    // The current data array
    UPROPERTY(BlueprintReadOnly, Category = Webcam)
    TArray<FColor> Data;

protected:

    // Use this function to update the texture rects you want to change:
    // NOTE: There is a method called UpdateTextureRegions in UTexture2D but it is compiled WITH_EDITOR and is not marked as ENGINE_API so it cannot be linked
    // from plugins.
    // FROM: https://wiki.unrealengine.com/Dynamic_Textures
    void UpdateTextureRegions(UTexture2D* Texture, int32 MipIndex, uint32 NumRegions, FUpdateTextureRegion2D* Regions, uint32 SrcPitch, uint32 SrcBpp, uint8* SrcData, bool bFreeData);

    // Pointer to update texture region 2D struct
    FUpdateTextureRegion2D* VideoUpdateTextureRegion;
};
```

#### Source

```cpp
// A simple webcam reader using the OpenCV library
// Author: The UE4 community

#include "YOURPROJECT.h"
#include "WebcamReader.h"

// Sets default values
AWebcamReader::AWebcamReader()
{
     // Set this actor to call Tick() every frame.  You can turn this off to improve performance if you don't need it.
    PrimaryActorTick.bCanEverTick = true;

    // Initialize OpenCV and webcam properties
    CameraID = 0;
    RefreshRate = 15;
    isStreamOpen = false;
    VideoSize = FVector2D(0, 0);
    ShouldResize = false;
    ResizeDeminsions = FVector2D(320, 240);
    RefreshTimer = 0.0f;
    stream = cv::VideoCapture();
    frame = cv::Mat();
}

// Called when the game starts or when spawned
void AWebcamReader::BeginPlay()
{
    Super::BeginPlay();

    // Open the stream
    stream.open(CameraID);
    if (stream.isOpened())
    {
        // Initialize stream
        isStreamOpen = true;
        UpdateFrame();
        VideoSize = FVector2D(frame.cols, frame.rows);
        size = cv::Size(ResizeDeminsions.X, ResizeDeminsions.Y);
        VideoTexture = UTexture2D::CreateTransient(VideoSize.X, VideoSize.Y);
        VideoTexture->UpdateResource();
        VideoUpdateTextureRegion = new FUpdateTextureRegion2D(0, 0, 0, 0, VideoSize.X, VideoSize.Y);

        // Initialize data array
        Data.Init(FColor(0, 0, 0, 255), VideoSize.X * VideoSize.Y);

        // Do first frame
        DoProcessing();
        UpdateTexture();
        OnNextVideoFrame();
    }

}

// Called every frame
void AWebcamReader::Tick( float DeltaTime )
{
    Super::Tick( DeltaTime );

    RefreshTimer += DeltaTime;
    if (isStreamOpen && RefreshTimer >= 1.0f / RefreshRate)
    {
        RefreshTimer -= 1.0f / RefreshRate;
        UpdateFrame();
        DoProcessing();
        UpdateTexture();
        OnNextVideoFrame();
    }
}

void AWebcamReader::UpdateFrame()
{
    if (stream.isOpened())
    {
        stream.read(frame);
        if (ShouldResize)
        {
            cv::resize(frame, frame, size);
        }
    }
    else {
        isStreamOpen = false;
    }
}

void AWebcamReader::DoProcessing()
{
    // TODO: Do any processing here!
}

void AWebcamReader::UpdateTexture()
{
    if (isStreamOpen && frame.data)
    {
        // Copy Mat data to Data array
        for (int y = 0; y < VideoSize.Y; y++)
        {
            for (int x = 0; x < VideoSize.X; x++)
            {
                int i = x + (y * VideoSize.X);
                Data[i].B = frame.data[i * 3 + 0];
                Data[i].G = frame.data[i * 3 + 1];
                Data[i].R = frame.data[i * 3 + 2];
            }
        }

        // Update texture 2D
        UpdateTextureRegions(VideoTexture, (int32)0, (uint32)1, VideoUpdateTextureRegion, (uint32)(4 * VideoSize.X), (uint32)4, (uint8*)Data.GetData(), false);
    }
}

void AWebcamReader::UpdateTextureRegions(UTexture2D* Texture, int32 MipIndex, uint32 NumRegions, FUpdateTextureRegion2D* Regions, uint32 SrcPitch, uint32 SrcBpp, uint8* SrcData, bool bFreeData)
{
    if (Texture->Resource)
    {
        struct FUpdateTextureRegionsData
        {
            FTexture2DResource* Texture2DResource;
            int32 MipIndex;
            uint32 NumRegions;
            FUpdateTextureRegion2D* Regions;
            uint32 SrcPitch;
            uint32 SrcBpp;
            uint8* SrcData;
        };

        FUpdateTextureRegionsData* RegionData = new FUpdateTextureRegionsData;

        RegionData->Texture2DResource = (FTexture2DResource*)Texture->Resource;
        RegionData->MipIndex = MipIndex;
        RegionData->NumRegions = NumRegions;
        RegionData->Regions = Regions;
        RegionData->SrcPitch = SrcPitch;
        RegionData->SrcBpp = SrcBpp;
        RegionData->SrcData = SrcData;

        ENQUEUE_UNIQUE_RENDER_COMMAND_TWOPARAMETER(
            UpdateTextureRegionsData,
            FUpdateTextureRegionsData*, RegionData, RegionData,
            bool, bFreeData, bFreeData,
            {
            for (uint32 RegionIndex = 0; RegionIndex < RegionData->NumRegions; ++RegionIndex)
            {
                int32 CurrentFirstMip = RegionData->Texture2DResource->GetCurrentFirstMip();
                if (RegionData->MipIndex >= CurrentFirstMip)
                {
                    RHIUpdateTexture2D(
                        RegionData->Texture2DResource->GetTexture2DRHI(),
                        RegionData->MipIndex - CurrentFirstMip,
                        RegionData->Regions[RegionIndex],
                        RegionData->SrcPitch,
                        RegionData->SrcData
                        + RegionData->Regions[RegionIndex].SrcY * RegionData->SrcPitch
                        + RegionData->Regions[RegionIndex].SrcX * RegionData->SrcBpp
                        );
                }
            }
            if (bFreeData)
            {
                FMemory::Free(RegionData->Regions);
                FMemory::Free(RegionData->SrcData);
            }
            delete RegionData;
        });
    }
}
```

Note: you need to change `YOURPROJECT` in the *class definition of the header file* and the project include in the source file with the correct version, which is based on your project's name.

This class is used as a wrapper for a future unreal blueprint class. It allows you to specify the device ID, target resolution and framerate of the camera, as well as providing a dynamic texture and an `FColor` array of the current frame's pixels and a blueprint native event that is called whenever the next webcam frame is available!

## Moving to Blueprints

You can now access your webcam feed in blueprints. From this point forward we will be working in the editor.

### Adding the WebcamBillboard Actor

Now that all the code has been included for accessing your webcams, I will now show you how to use the dynamic texture from the WebcamReader actor in a new WebcamBillboard subclass. This time, the code will be implemented in unreal blueprints! Launch the editor again with *Debug > Start* new instance. In your choice of directory, right click and add a new blueprint class. At the bottom of the new window, expand *All Classes* and search `AWebcamReader` and select it as the parent class. Name the new blueprint `BP_WebcamBillboard` and open it.

Within the viewport, add a cube static mesh component, and name it `Billboard`. This will be the component that the texture is rendered to. At the beginning of the game, we will want to create a dynamic material instance and set it to the billboard mesh. Under *Variables*, click the + button to add a new *Material Instance Dynamic* called `DynamicMaterial`’ Drag the `Billboard` component onto the Event Graph, and create a *getter* node. Drag out from this new getter and create a *Create Dynamic Material Instance* node and connect the white execution wire to the transparent *BeginPlay* event (or create one). This creates an special Unreal material instance that can be altered at runtime. However, we have not created this Unreal material!

Go back to your content browser, right click and create a new material. Call this material `M_Webcam` and open it. Click on the `M_Webcam` node and set the *Shading Mode* to *Unlit*. Hold `T` and left click anywhere in the new graph to create a texture node. You will have to set the default texture to anything (I used `T_Ceramic_Tile_M`). Right click this node and convert it to a parameter. Call this parameter *Texture* and connect its white `Float3` pin to the *Emissive Color* pin on the `M_Webcam` node. Make sure the save the material!

Now, back in the `BP_WebcamBillboard` blueprint, select the `M_Webcam` as the *Source Material* for the *Create Dynamic Material Instance* node, and make sure the *Element Index* is set to `0`. Drag out from the original billboard getter and create a *Set Material* node. Set the *Material* pin to the output of the *Create Dynamic Material Instance* node, and again make sure the *Element Index* is set to `0`. Finally, drag out the *DynamicMaterial* variable we created earlier and create a setter. Connect the output of the *Create Dynamic Material Instance* node to the *DynamicMaterial* input pin to save a reference of this special material for later use.

We have dynamically set the material of our *Billboard* mesh, and now we need to update its texture parameter each time a new frame is received. To do this, right click on the *Event Graph* and create a *OnNextVideoFrame* event. This event is called in the `AWebcamReader` actor whenever a new frame is read. Drag out the *DynamicMaterial* variable and create a getter underneath the new event. Drag out from the getter and create a *Set Texture Parameter Value* node. Set the *Parameter Name* to *Texture* (the name of the texture parameter in the `M_Webcam` material). Right click on the *Event Graph* and type *VideoTexture* to retrieve a reference to the webcam texture provided by the `AWebcamReader` parent class. Connect the output pin of this *VideoTexture* reference to the *Value* pin of the *Set Texture Parameter Value* node. With that, the `BP_WebcamBillboard` is ready for use!

Drag the `BP_WebcamBillboard` blueprint from the content browser into your level. Orientate and position it however you like, and scale it to a similar scale of your images resolution (about `6.4`, `4.8`, and `0.5` for my webcam). Now, set the Webcam properties in the detail panel. (I used a *Camera ID* of `0`, *Should Resize* to `false`, and *Refresh Rate* of `2.0`) Your *Camera ID* will determine the camera that renders, it should be `0` unless you have more than one webcam. In the case of a laptop, `0` will probably be the integrated laptop, and `1+` will be any additional webcams. You can now press play to see the results!

![Project Creation](https://3425263208-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M3mx7Lszp8LdwKKD7yR%2F-M462J1RJdKu8dvwBJxs%2F-M462KI_tlzYuo42EWPr%2Fadding-the-webcam-to-a-level.png?generation=1586034999114250\&alt=media)

You can hold alt and move the object to duplicate it. Change its Camera ID to render a second webcam!

![Project Creation](https://3425263208-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M3mx7Lszp8LdwKKD7yR%2F-M462J1RJdKu8dvwBJxs%2F-M462KIbhFQHV753Qkzw%2Fadding-the-webcam-to-a-level2.png?generation=1586034998236324\&alt=media)

Good luck with your OpenCV / UE4 Projects! :)

## Final Notes

For packaged versions of your OpenCV projects, be sure that the executable has access to the dll's. For a windows build, this can be done by coppying the *opencv\_world320.dll* and *opencv\_ffmpeg320\_64.dll* into the `WindowsNoEditor/YOURPROJECT` directory. (There are 2 executables for windows builds, but the one in the `YOURPROJECT` directory is the one that needs access to the dll's, regardless of which one you use to launch your project!)

UE4 and the C++ standard library do not play well together. This can cause annoying crashes, such as with the `cv::findContours` function (often during the `std::vector` destructors). Members of the community have gotten around this by wrapping `findContour` calls in a separate library, and including that in their UE4 projects with steps similar to the ones to include the OpenCV library in this tutorial.

The webcam reader shown in this tutorial is designed to be simple and easy to follow. However, it isn't very efficient, as all of the OpenCV reading code and UE4 dynamic texture code occurs on the game thread, potentially per-tick with high refresh rates! I would recommend separating these parts into another thread to increase performance. Rama's tutorial on multi-threading is a good start if you are unfamiliar with UE4 threads.

If any of these points are confusing, feel free to say so on my talk page and when I get the chance I will add an in-depth section to this tutorial! :)

-Ginku


# Introduction

This guide aims to be a new community resource for Unreal Engine 4. The first initiative behind this guide is to find and preserve as much of the original Unreal Engine 4 Wiki as possible. In addition to preserving the original wiki content, we're also planning on publishing new and updated content that may be useful to the Unreal development community. This can be seen with the new "Quick Reference" section.

If you're looking to help us in the archiving effort, [click here](/wiki-archives#a-new-community-driven-wiki-was-launched-for-unreal-engine-4).

## I want to contribute, how can I help?

1. [Fork the repository for this site on Github](https://github.com/NickGlenn/Unreal-Engine-4-Community-Guide).
2. Create a Pull Request in Github for the changes made to the book.
3. Assign [@nickglenn](https://github.com/nickglenn) as a reviewer.


# Quick Reference


# C++ Data Type Snippets

This page contains several code snippets for quickly creating C++ data types that can be used with Blueprints. Use this as reference or as a copy + paste resource as needed.

## Interfaces

For more information about interfaces in Unreal, [check out this wiki article](/wiki-archives/macros-and-data-types/interfaces-in-c++).

* You need to define two classes: `U<Name>` and `I<Name>`. The second class is what your C++ code will extend to implement the interface.

```cpp
UINTERFACE(BlueprintType)
class MYPROJECT_API UExample : public UInterface
{
  GENERATED_BODY()
};

class MYPROJECT_API IExample
{
  GENERATED_BODY()

public:

  UFUNCTION(BlueprintNativeEvent, BlueprintCallable)
  bool NativeEventExampleMethod();

  UFUNCTION(BlueprintImplementableEvent, BlueprintCallable)
  bool BlueprintEventExampleMethod();

};
```

## Structs

For more information about structs in Unreal, [check out this wiki article](/wiki-archives/macros-and-data-types/structs-ustructs-theyre-awesome).

* To access your struct from Blueprint, make sure to add the `BlueprintType` keyword to the `USTRUCT` macro.
* Structs must have a default constructor.
* It's Unreal coding standard to prefix your structs with a capital `F`.
* You cannot use the `UFUNCTION` macro with methods on structs.

```cpp
USTRUCT(BlueprintType)
struct MYPROJECT_API FExample
{
    GENERATED_BODY()
    
public:

    UPROPERTY(BlueprintReadOnly)
    int32 SomeValue;

};
```


# The UPROPERTY Macro

A quick reference around Unreal's UPROPERTY macro in C++ and available attributes.

> This article is a work in progress, come back later.


# The UFUNCTION Macro

A quick reference around Unreal's UFUNCTION macro in C++ and available keywords.

## Keywords

These keywords are also valid for the `UDELEGATE` macro.

### **BlueprintAuthorityOnly**

This function will only execute from Blueprint code if running on a machine with network authority (a server, dedicated server, or single-player game).

* Useful for visually marking methods in Blueprint for designers.
* Will still execute on non-network authority clients when called from C++.

```cpp
UFUNCTION(BlueprintCallable, BlueprintAuthorityOnly)
void SpawnProjectile();
```

### **BlueprintCallable**

&#x20;This function can be executed in a Blueprint and will appear in Blueprint tooling.

* Using the `const` C++ keyword on the related method will remove the execution pin, making this a pure Blueprint function node.

```cpp
UFUNCTION(BlueprintCallable)
void SetValue(float InValue);
```

### **BlueprintCosmetic**

This function is cosmetic and will not run on dedicated servers.

* Will still execute on network authority servers when called from C++.

```cpp
UFUNCTION(BlueprintImplementableEvent, BlueprintCosmetic)
void PlayHitEffects();
```

### BlueprintGetter

&#x20;This function will be used as the accessor for a Blueprint-exposed property. This specifier implies `BlueprintPure` and `BlueprintCallable`.

> More information needed about this keyword.

### BlueprintInternalUseOnly

Indicates that the function should not be exposed to the end user.

> More information needed about this keyword.

### BlueprintImplementableEvent

This function is designed to be overridden (implemented) in Blueprint.

* Do not provide a body for this function; the auto-generated code will include a thunk that calls `ProcessEvent` to execute the overridden body.
* You'll need to add the `BlueprintCallable` keyword if you want to call this function from Blueprint, otherwise it's only callable via C++.

```cpp
UFUNCTION(BlueprintImplementableEvent)
void OnSomethingHappened();
```

### BlueprintNativeEvent

This function is designed to be overridden in Blueprint, but also has a native (C++) implementation.

* To create a native implementation of the function, you'll need to define a method named `[FunctionName]_Implementation` instead of just the function name. This is due to how the auto-generated code will include a thunk that calls the implementation method when necessary.
* You'll need to add the `BlueprintCallable` keyword if you want to call this function from Blueprint, otherwise it's only callable via C++.

{% tabs %}
{% tab title="Example.h" %}

```cpp
UFUNCTION(BlueprintNativeEvent)
void DoSomething();
```

{% endtab %}

{% tab title="Example.cpp" %}

```cpp
void Example::DoSomething_Implementation() {
    // Your code here
}
```

{% endtab %}
{% endtabs %}

### **BlueprintPure**

The function does not affect the owning object in any way and can be executed in a Blueprint.

* It's effectively the same as marking a method as `BlueprintCallable` with the `const` C++ keyword.
* These functions must have a return type.
* It is not required, but generally recommended that the function be marked `const`.

```cpp
UFUNCTION(BlueprintPure)
float GetValue() const;
```

### **BlueprintSetter**

&#x20;This function will be used as the mutator for a Blueprint-exposed property. This specifier implies `BlueprintCallable`.

> More information needed about this keyword.

### CallInEditor

This function can be called in the editor on selected instances via a button in the Details panel.

> More information needed about this keyword.

### **Category**

Specifies the category of the function when displayed in Blueprint editing tools.&#x20;

* You can define nested categories using the `|` operator.
* Quotes are only required when adding spaces or the `|` operator.

```cpp
UFUNCTION(BlueprintCallable, Category="Weapon|Gun")
void Fire();
```

### **Client**

&#x20;The function is only executed on the client that owns the Object on which the function is called. See [Unreal's documentation on RPCs](https://docs.unrealengine.com/en-US/Gameplay/Networking/Actors/RPCs/index.html) for more information.

* Declares an additional function named the same as the main function, but with `_Implementation` added to the end. The auto-generated code will call the `_Implementation` method when necessary.
* Owning client is the object with `ENetRole` of `AutonomousProxy`.
* RPC functions should not have a return value.
* RPC functions are unreliable by default.

```cpp
UFUNCTION(Client)
void ReportHit(float Damage, FVector Direction);
```

### **Custom Thunk**

The `UnrealHeaderTool` code generator will not produce a thunk for this function; it is up to the user to provide one.

> More information needed about this keyword.

### **Exec**

This function is executable from the command line. For more information, [check out this wiki article about the Exec Functions](/wiki-archives/common-pitfalls/exec-functions).

```cpp
UFUNCTION(Exec)
void GodMode(bool bEnabled);
```

### NetMulticast

&#x20;The function is executed both locally on the server, and replicated to all clients, regardless of the Actor's `NetOwner`. See [Unreal's documentation on RPCs](https://docs.unrealengine.com/en-US/Gameplay/Networking/Actors/RPCs/index.html) for more information.

* Declares an additional function named the same as the main function, but with `_Implementation` added to the end. The auto-generated code will call the `_Implementation` method when necessary.
* Multicast RPCs behave differently when called by the network authority (server) or client:
  * If they are called from the server, the server will execute them locally as well as execute them on all currently connected clients.
  * If they are called from clients, they will only execute locally, and will not execute on the server.
* Multicast functions are throttled and will not replicate more than twice in a given Actor's network update period.
* RPC functions should not have a return value.
* RPC functions are unreliable by default.

```cpp
UFUNCTION(NetMulticast)
void BroadcastGameplayEvent(EGameplayEventType EventType);
```

### **Reliable**

The function is replicated over the network, and is guaranteed to arrive regardless of bandwidth or network errors. Only valid when used in conjunction with the `Client` or `Server` keywords.

```cpp
UFUNCTION(Client, Reliable)
void SendPrivateMessage(FString Text);
```

### **SealedEvent**

&#x20;This function cannot be overridden in sub-classes. The `SealedEvent` keyword can only be used for events. For non-event functions, declare them as `static` or `final` to seal them.

```cpp
UFUNCTION(BlueprintNativeEvent, SealedEvent)
void DoSomething();
```

### **ServiceRequest**

This function is an RPC (Remote Procedure Call) service reques&#x74;**.**

> More information needed about this keyword.

### ServiceResponse

This function is an RPC service response.

> More information needed about this keyword.

### **Server**

&#x20;The function is only executed on the server. See [Unreal's documentation on RPCs](https://docs.unrealengine.com/en-US/Gameplay/Networking/Actors/RPCs/index.html) for more information.

* Declares an additional function named the same as the main function, but with `_Implementation` added to the end, which is where code should be written. The auto-generated code will call the `_Implementation` method when necessary.
* The `WithValidation` keyword must be used with the `Server` keyword.
* RPC functions should not have a return value.
* RPC functions are unreliable by default.

```cpp
UFUNCTION(Server, WithValidation)
void ServerSendInputValue(float Value);
```

### **Unreliable**

The function is replicated over the network but can fail due to bandwidth limitations or network errors.&#x20;

* Only valid when used in conjunction with `Client` or `Server`.

```cpp
UFUNCTION(Client, Unreliable)
void SendObjectLocation(FVector Location);
```

### **WithValidation**

Declares an additional function named the same as the main function, but with `_Validate` added to the end. This function takes the same parameters, and returns a `bool` to indicate whether or not the call to the main function should proceed.

* Required for the `Server` keyword. This was done to encourage secure server RPC functions, and to make it as easy as possible for someone to add code to check each and every parameter to be valid against all the known input constraints.

{% tabs %}
{% tab title="MyCharacter.h" %}

```cpp
UFUNCTION(Server, Reliable, WithValidation)
void ServerSetSprint(bool bSprinting);
```

{% endtab %}

{% tab title="MyCharacter.cpp" %}

```cpp
void AMyCharacter::ServerSetSprint_Implementation(bool bSprinting) {
  SetSprint(bSprinting);
}

bool AMyCharacter::ServerSetSprint_Validate(bool bSprinting) {
  return true;
}
```

{% endtab %}
{% endtabs %}

## Additional Resources

* [Unreal Official Documentation: UFunctions](https://docs.unrealengine.com/en-US/Programming/UnrealArchitecture/Reference/Functions/index.html)
* [Tom Looman: UFUNCTION Keywords Explained](https://www.tomlooman.com/ue4-ufunction-keywords-explained/)


# Wiki Archives

Epic's choice to take down the wiki came quick. This guide hopes to help developers looking for the content that used to be found on Epic's now defunct Wiki.

## So the community Wiki is gone, now what?

~~It would be shocking if Epic didn't wind up putting the Wiki back only, at least for a temporary amount of time. But in the event that they don't (or if it takes them a while to do so), we can do our best to retain and archive as much of the wiki on this site.~~

![](https://media.giphy.com/media/8qr5b7fs7JqxrvEOzH/giphy.gif)

Since this news broke a number of things have happened and this page was first created, a number of things have happened. As a result, this guidebook will become more of a resource manual that offers guidance of a focused set of topics that will independently maintained by a smaller group of developers.

### A new community-driven wiki was launched for Unreal Engine 4

A **community** effort has been launched to create a new wiki resource for developers. You can check out the new wiki using the link below. Heads up though, it's still in a work in progress!

{% embed url="<https://ue4community.wiki>" %}

In addition to the new wiki, there's a community driven Discord channel around this effort. We'd love to have anyone looking to contribute to the conversation around building a better platform for Unreal Engine and game development knowledge-share.

{% embed url="<https://discord.gg/GsEw5z4>" %}

### Epic released a static file dump of the wiki contents

One of Epic's community managers reached out to us (the community mentioned above) and provided access to an archive of all the original wiki files. It's hosted on Box and you can access it using the link below. If you can't find the article you're looking for on the new wiki, or want the original version of the content, then that's going to be the place to look.

{% embed url="<https://epicgames.ent.box.com/s/2e5hhlvqyu9octooxbkgwt2xdmmrea9z>" %}

### Other members of the community started publishing their own archives

Several other members have created solutions for getting the old wiki content online. For example, [Michael Cole](https://github.com/michaeljcole) did a great job of building a quick Github pages solution using the Wayback Machine archive content.

{% embed url="<https://michaeljcole.github.io/wiki.unrealengine.com/>" %}

### I can't find the article I'm looking for...

We've gone ahead and scoured the Wayback Machine in order to a create a `.zip` file with as much archival data as we could retrieve. This file is available for download on Dropbox using the following link:

{% embed url="<https://www.dropbox.com/s/g7plgzei399v342/wiki.unrealengine.com.zip?dl=0>" %}

If you can't find it in the `.zip` archive, changes are that it's lost for good until Epic or the original author reposts it somewhere else.


# Debugging & Utilities


# Exec Functions

### Overview

Exec functions are pretty cool and super useful, especially in development. They let you call functions from the command line. The crappy part is they are poorly documented and have a lot of caveats and hidden functionality, so I wanted to make this page as a catching point until the exec documentation gets better.

### What Are They?

So what are exec functions. Pretty much exec functions are a simple way to declare console accessible functions through the UFUNCTION macro system easily by just adding the "Exec" command. The console commands kind of cascade their way down through either the player controllers or viewport until they are handled at some point in the chain.

They're called simply from the console by pressing the \~ key on most keyboards and typing the name of your function with any arguments entered after.

### What Classes Can Have Exec Functions?

Only some classes support Exec functions out of the box. Possessed Pawns, Player Controllers, Player Input, Cheat Managers, Game Modes, Game Instances, overriden Game Engine classes, and Huds should all work by just adding the standard UFUNCTION markup. Exec functions tend to cascade down to these classes through the player controller (Pawn/Player Controllers/Cheat Manager/etc.) or the game viewport (game instance/game mode/etc). If there is something amiss with either of those, you will probably run into issues with your exec functions running at all.

There are some other classes that are supported out of the box, but they're mostly other ways of getting to the above classes and are probably better to avoid if you don't know what you're doing.

As far as how to support classes that aren't supported out of the box, see the section below on how to support exec functions in classes that don't natively support them.

### How Do I Declare Them?

Declaring an exec function is super simple.

```cpp
   UFUNCTION(Exec)
   void YourExecFunction();
```

Called just by entering it in the command line like so:

![](https://web.archive.org/web/20191020173554im_/https://d26ilriwvtzlb.cloudfront.net/e/ed/ExecFuncNoArg.PNG)

Adding arguments is also simple.

```cpp
   UFUNCTION(Exec)
   void YourExecFunction(int32 arg1, FString arg2);
```

With your arguments separated by spaces.

![ExecFuncWithArgs.PNG](https://web.archive.org/web/20191020173554im_/https://d26ilriwvtzlb.cloudfront.net/4/4a/ExecFuncWithArgs.PNG)

### How Do I Get Other Classes to Support Exec Functions?

So the main reason I wanted to write this up was because of this cool feature. It's possible to get Exec functions working on any UObject class you want. The only caveat is that you need to make sure an instance of that object is somehow accessible from one of the classes above. Preferably you'll want only one instance of that class to be accessible from above. I use this mostly just to keep classes from becoming overcrowded with exec functions that just pipe the call to a member anyway. It's really easy to fall into the trap of having one class be an exec function dumping ground for your whole game.

Anyway, how do you do it? This is actually also really simple. The unreal header tool does most of the footwork generating the Exec function's metadata already, so all you really need to do is forward the ProcessConsoleExec function from an Exec capable class to an instance of the class you want to call Exec functions on under it.

In the header:

```cpp
   virtual bool ProcessConsoleExec(const TCHAR* Cmd, FOutputDevice& Ar, UObject* Executor) override;
```

In the cpp:

```cpp
   bool YourExecCapableClass::ProcessConsoleExec(const TCHAR* Cmd, FOutputDevice& Ar, UObject* Executor)
   {
       bool handled = Super::ProcessConsoleExec(Cmd, Ar, Executor);
       if (!handled)
       {
               handled &= _yourNewExecInstance->ProcessConsoleExec(Cmd, Ar, Executor);
       }
       return handled;
   }
```

You shouldn't even have to override anything on your new class because the processing is handled by the UObject interface. All you have to do is call it.


# How To Prevent Crashes Due To Dangling Actor Pointers

This wiki article was written by Rama.

While working on Abatron, an RTS/FPS hybrid game with tons of character units to keep track of, I created a lot of arrays of Actors:

```cpp
TArray<AActor*> UnitArray;
```

During multiplayer testing especially, stale / dangling AActor pointers were causing a lot of crashes!

The problem with stale pointers is that just checking ActorPtr != nullptr is not enough, a stale pointer will return true but wont actually still be pointing to a valid AActor, which is what causes the crash.

### UPROPERTY() UObjects Clear References Properly

A less-advertised feature of UObject pointers that are made UPROPERTY() is that they are properly updated to NULL when the object is destroyed, unlike raw pointers like I was using above.

Automatic Updating of UObject References <https://docs.unrealengine.com/latest/INT/Programming/UnrealArchitecture/Objects/Optimizations/index.html#automaticupdatingofreferences>

So the **simple solution** if you are having issues with dangling / stale actor pointers is to make sure all AActor pointers are marked with UPROPERTY().

```cpp
UPROPERTY() //<~~~ That's it! This now makes the pointers much more stable! -Rama
TArray<AActor*> UnitArray;
```

### TWeakObjectPtr

For UObjects especially, having lots of UPROPERTY() references to them can prevent them from getting garbage collected properly. For this situation you can use TWeakObjectPtr which will still give you additional validity option using IsValid() but will not prevent GC from running.

### Conclusion

If you are encountering AActor\* pointers that are going stale and crashing your game, make sure they are marked with UPROPERTY() and you will be taking advantage of a rather essential feature of UObjects in UE4, which is that all UPROPERTY() references get updated to NULL when a UObject is destroyed.

Have fun today!

Rama


# Profiling: How to Count CPU Cycles

This wiki article was written by Rama.

## Overview

In this wiki I show you how you can count the CPU cycles of individual blocks of your game code, and expose this information to a very easy-to-use UI in the UE4 Editor! This wiki shows you how to leverage all the work Epic engineers have put into the UE4 profiler, customizing it to monitor named sections of your game code! After you're done with this wiki you will be able to check on the performance of any individual lines or functions from your entire project-level code base, assigning your own chosen names to these blocks of code! Enjoy! Rama

### Pic of What This Wiki Enables You To Do

![We have our own stats now](https://930279451-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M3mx7Lszp8LdwKKD7yR%2F-M462J1RJdKu8dvwBJxs%2F-M462MQGxvvXIZuKznIE%2FWeHaveOurOwnStatsNow.jpg?generation=1586035009073238\&alt=media)

In this picture you can see I've created my own custom STAT so that the UE4 Profiler can track a specific block of my game code that I called **"Joy \~ PerformSphereMovement"**.

I've successfully tracked the CPU cycles of a section of my own project-level code base and exposed this information to the very friendly GUI of the UE4 Profiler!

Yay!

This picture shows that the UE4 Profiler has confirmed my guess that a certain block of my code was causing almost 97% (96.6) of the performance hit for all the character tick code in my entire code base!

It saves me hours of time to be able to easily narrow down what block of code in my rather large character code base is causing **literally 97% of the character-code performance hit!**

### UE4 Documentation on the Profiler

I assume you are familiar with the basics of the UE4 profiler in this tutorial.

If you have not yet seen what the profiler can already do for you, I recommend reading the Epic Documentation and trying it out!

[Epic Documentation on the Amazing UE4 Profiler](https://docs.unrealengine.com/en-US/Engine/Performance/Profiler/index.html)

### Running The UE4 Profiler

Type in the in-game console to Start Profile:

```
 "stat startfile";
```

Type in the in-game console To Stop Profile

```
 "stat stopfile";
```

### Opening Your Profiled Game Session Data in the Editor

Go to Window->Developer Tools->Session Front End

Then click on the profiler button!

![Session Frontend](https://930279451-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M3mx7Lszp8LdwKKD7yR%2F-M462J1RJdKu8dvwBJxs%2F-M462MQJlVn4mAOZwhPK%2FSessionFrontProfiler.jpg?generation=1586035010002378\&alt=media)

Then you can load your file that you saved!

It will be under the Saved/Profiling directory :)

Always check the date to make sure you are looking at the right file!

### Self

Now on to the core of this wiki!

You'll notice that in your game code there will be huge blocks called "Self" which indicates code that has not been divided up into cycle-counted sub-sections! This Self block is all of the code running for your in-game class instances.

Well here is how you can sub-divide Self into your own chosen named categories, neatly organizing and cateloging your own code base!

### Creating Your Own Stat Group

Let's say you have class hierachy of classes for your in-game Character.

You want to subdivide the inner workings of your entire character code into CPU cycle-counted code blocks.

In the highest level of your class structure, in the .h, declare your category

```cpp
//For UE4 Profiler ~ Stat Group
DECLARE_STATS_GROUP(TEXT("JoyBall"), STATGROUP_JoyBall, STATCAT_Advanced);
```

### Creating the Stat

In the .cpp where you want to track a particular function body, put this at the top just below the #includes

```cpp
/*
    By Rama
*/
#include "Joy.h"
#include "JoyBall.h"

//For UE4 Profiler ~ Stat
DECLARE_CYCLE_STAT(TEXT("Joy ~ PerformSphereMovement"), STAT_PerformSphereMovement, STATGROUP_JoyBall);
```

Please note you can create as many CYCLE\_STAT's as you want for your particular STATGROUP !

And you should have one DECLARE\_CYCLE\_STAT for each function body/scope that you want to count cycles for.

### Using the Stat

At the very top of the scope of the function you want to track, put the SCOPE macro. Everything within the brackets of the scope you put the SCOPE\_CYCLE\_COUNTER in will be cycle-counted by the profiler!

```cpp
void AJoyBallMovement::PerformSphereMovement()
{
    SCOPE_CYCLE_COUNTER(STAT_PerformSphereMovement);

    //... your code that you want to test the performance of and have show up in the profiler

} //Cycle count scope ends here -Rama
```

### Counting CPU Cycles For Any Block of Code

Please note your scope can be within a single function, just make sure to give such a stat an appropriate name like YourFunction\_Internal or something Again, the SCOPE\_CYCLE\_COUNTER will cycle-count within its brackets

```cpp
void AJoyBallMovement::PerformSphereMovement()
{
    //First part of this function, code that wont be cycle counted
    ConsoleCommand("Joy");
    //... etc

    //You can scope any lines of code you want by adding brackets!
    {
        SCOPE_CYCLE_COUNTER(STAT_PerformSphereMovement);
        int32 Parameter = 200;
        YourFunctionThatYouThinkMightBeSlow(Parameter);
        //other code to cycle count

    } //Cycle count scope ends here -Rama


    //More code that wont be cycle counted
    ConsoleCommand("~~~~~");
        //... etc
}
```

### Example From My Code Base

See the picture in the overview!

In my own code base I had a 10 class inheritance hierarchy for my game character, and the UE4 profiler was simply telling me that the character "Self" was costing 37% of my total performance hit.

I used the info I am sharing with you in this wiki to create a SCOPE\_CYCLE\_COUNTER for the function that I thought was probably taking all the performance, and I was right!

But the most important thing is that I enabled the awesome UE4 Profiler to help me narrow down the performance hit in my game code to just a single function / block of code, and so with that info I can easily address the performance hit, knowing it is worth the effort to rewrite the code!

### Conclusion

You now know how you can CPU cycle-count individual lines of your game code base, and expose this information to UE4's super awesome GUI Profiler!

Enjoy!


# Logs: Printing Messages to Yourself during Runtime

This wiki article was written by Rama; Converted by jfaw.

## Overview

Dear Community,

Logs are essential for giving yourself feedback as to whether

* Your new functions are even being called
* What data your algorithm is using during runtime
* Reporting errors to yourself and the end user / debugging team
* Imposing a fatal error to stop runtime execution in special circumstances

This page describes how to use the **Unreal output log**.

Other options are also discussed at the bottom of the page.

## Accessing Logs

### In-Game

To see logs you must run your game with `-Log` (you must create a shortcut to the Editor executable and add `-Log` to the end).

or use console command "showlog" in your game.

### Within Editor (Play-In-Editor)

Log messages are sent to the 'Output' log which is accessible via *Window -> Developer Tools -> Output Log*.

If you are using the Editor and PIE, logging should be enabled by default due to the presence of `GameCommandLine=-log` in your Engine INI file. If no logging is visible, add the `-Log` command line option as per the instructions for In-Game logging above.

### Quick Usage

```cpp
UE_LOG(LogTemp, Warning, TEXT("Your message"));
```

This way you can log without the need of creating a custom category. Doing so will keep everything clean and sorted though.

### Log Verbosity Levels

Log verbosity levels are used to more easily control what is being printed, allowing you to keep even the most detailed log statements in your code without having them spam output when you don't want them to. Each log statement declares which log it belongs to and it's verbosity level. Verbosity level is controlled on a per-log basis.

Each log's verbosity is controlled by four things: 1. Compile-time verbosity 2. Default verbosity 3. `.ini` verbosity 4. Runtime-verbosity.

If a log statement is more verbose than it's log's compile time verbosity it won't even be compiled into the game code. From there the log's level is set to the default verbosity, which can then be overridden in the Engine.ini file, either of those can then be overridden from the command line (the runtime verbosity). Once the game (or editor) is running it may not be possible to change a log category's verbosity (I am not sure, someone who knows please correct this).

Here are the verbosity levels available to use:

* **Fatal** Fatal level logs are always printed to console and log files and crashes even if logging is disabled.
* **Error** Error level logs are printed to console and log files. These appear red by default.
* **Warning** Warning level logs are printed to console and log files. These appear yellow by default.
* **Display** Display level logs are printed to console and log files.
* **Log** Log level logs are printed to log files but not to the in-game console. They can still be viewed in editor as they appear via the Output Log window.
* **Verbose** Verbose level logs are printed to log files but not the in-game console. This is usually used for detailed logging and debugging.
* **VeryVerbose** VeryVerbose level logs are printed to log files but not the in-game console. This is usually used for very detailed logging that would otherwise spam output.

For the `CompileTimeVerbosity` parameter of `DECLARE_LOG_CATEGORY_EXTERN` it is also valid to use `All` (functionally the same as using `VeryVerbose`) or `NoLogging` (functionally the same as using `Fatal`).

## Setting Up Your Own Log Category

### Log Category Macros

The macros `DECLARE_LOG_CATEGORY_EXTERN` and `DEFINE_LOG_CATEGORY` go in *YourGame.h* and *YourGame.cpp* respectively.

The macro to declare a log category has three parameters. Each declared log category should have a corresponding defined log category in a cpp.

```cpp
DECLARE_LOG_CATEGORY_EXTERN(CategoryName, DefaultVerbosity, CompileTimeVerbosity);
```

`CategoryName` is simply the name for the new category you are defining.

`DefaultVerbosity` is the verbosity level used when one is not specified in the ini files or on the command line. Anything more verbose than this will not be logged.

`CompileTimeVerbosity` is the maximum verbosity to compile in the code. Anything more verbose than this will not be compiled.

The macro to define a log category takes only the name of the category.

```cpp
DEFINE_LOG_CATEGORY(CategoryName);
```

### Usage Example

You can have different log categories for different aspects of your game!

This gives you additional info, because `UE_LOG` prints out which log category is displaying a message.

Here is an example of where the different log levels start to become useful.

Say you're often having trouble with a certain system in your game. In debugging you might want very detailed logs, but when you've finished debugging for now you know you might need those detailed logs later on, but they're spamming the output. What do you do? Use different log levels.

#### MyGame.H

```cpp
//General Log
DECLARE_LOG_CATEGORY_EXTERN(LogMyGame, Log, All);

//Logging during game startup
DECLARE_LOG_CATEGORY_EXTERN(LogMyGameInit, Log, All);

//Logging for your AI system
DECLARE_LOG_CATEGORY_EXTERN(LogMyGameAI, Log, All);

//Logging for a that troublesome system
DECLARE_LOG_CATEGORY_EXTERN(LogMyGameSomeSystem, Log, All);

//Logging for Critical Errors that must always be addressed
DECLARE_LOG_CATEGORY_EXTERN(LogMyGameCriticalErrors, Log, All);
```

#### MyGame.CPP

```cpp
#include "MyGame.h"

//General Log
DEFINE_LOG_CATEGORY(LogMyGame);

//Logging during game startup
DEFINE_LOG_CATEGORY(LogMyGameInit);

//Logging for your AI system
DEFINE_LOG_CATEGORY(LogMyGameAI);

//Logging for some system
DEFINE_LOG_CATEGORY(LogMyGameSomeSystem);

//Logging for Critical Errors that must always be addressed
DEFINE_LOG_CATEGORY(LogMyGameCriticalErrors);
```

#### MyClass.CPP

```cpp
//...
void UMyClass::FireWeapon()
{
    UE_LOG(LogMyGameSomeSystem, Verbose, TEXT("UMyClass %s entering FireWeapon()"), *GetNameSafe(this));
    //Logic
    UE_LOG(LogMyGameSomeSystem, Verbose, TEXT("UMyClass %s Attempting to fire."), *GetNameSafe(this));
    if (CheckSomething())
    {
        UE_LOG(LogMyGameSomeSystem, Log, TEXT("UMyClass %s is firing their weapon with charge of %f"), *GetNameSafe(this), GetCharge());
        //Firing logic
    }
    else
    {
        UE_LOG(LogMyGameSomeSystem, Error, TEXT("UMyClass %s CheckSomething() returned false during FireWeapon(), this is bad!"), *GetNameSafe(this));
        //Fail with grace
    }
    //More code!
    UE_LOG(LogMyGameSomeSystem, Verbose, TEXT("UMyClass %s leaving FireWeapon()"), *GetNameSafe(this));
}

void UMyClass::Tick(float DeltaTime)
{
    UE_LOG(LogMyGameSomeSystem, VeryVerbose, TEXT("UMyClass %s's charge is %f"), *GetNameSafe(this), GetCharge());
    if (something)
    {
        UE_LOG(LogMyGameSomeSystem, VeryVerbose, TEXT("Idk"));
    }
    if (somethingelse)
    {
        UE_LOG(LogMyGameSomeSystem, VeryVerbose, TEXT("Stuff"));
    }
}
//...
```

When you're not working on this system all these log statements would absolutely flood your output, and even when you are working on it you might not want the level of detail that is putting out multiple logs per tick.

By using log levels you can simply change the verbosity in the category's declaration, in the ini files, or on the command line to hide/reveal different layers of log statements as you need them. Ex:

```cpp
//All log statements are shown.
DECLARE_LOG_CATEGORY_EXTERN(LogMyGameSomeSystem, Log, All);

//VeryVerbose statements won't be shown.
DECLARE_LOG_CATEGORY_EXTERN(LogMyGameSomeSystem, Verbose, All);

//Neither VeryVerbose nor Verbose statements will be shown.
DECLARE_LOG_CATEGORY_EXTERN(LogMyGameSomeSystem, VeryVerbose, All);
```

The log categories used by Unreal Engine use different log levels, but by default have a higher `CompileTimeVerbosity`. In debugging interaction with Unreal code it might be helpful to turn up the verbosity of Unreal code in *DefaultEngine.ini* under `[Core.Log]` by adding an entry like `LogOnline=Verbose`.

## Log Formatting

#### Log Message

```cpp
//"This is a message to yourself during runtime!"
UE_LOG(YourLog,Warning,TEXT("This is a message to yourself during runtime!"));
```

#### Log an FString

* `%s` strings are wanted as `TCHAR*` by `Log`, so use `*FString()`

```cpp
//"MyCharacter's Name is %s"
UE_LOG(YourLog,Warning,TEXT("MyCharacter's Name is %s"), *MyCharacter->GetName() );
```

#### Log an Bool

```cpp
//"MyCharacter's Bool is %s"
UE_LOG(YourLog,Warning,TEXT("MyCharacter's Bool is %s"), (MyCharacter->MyBool ? TEXT("True") : TEXT("False")));
```

#### Log an Int

```cpp
//"MyCharacter's Health is %d"
UE_LOG(YourLog,Warning,TEXT("MyCharacter's Health is %d"), MyCharacter->Health );
```

#### Log a Float

```cpp
//"MyCharacter's Health is %f"
UE_LOG(YourLog,Warning,TEXT("MyCharacter's Health is %f"), MyCharacter->Health );
```

#### Log an FVector

```cpp
//"MyCharacter's Location is %s"
UE_LOG(YourLog,Warning,TEXT("MyCharacter's Location is %s"), 
    *MyCharacter->GetActorLocation().ToString());
```

#### Log an FName

```cpp
//"MyCharacter's FName is %s"
UE_LOG(YourLog,Warning,TEXT("MyCharacter's FName is %s"), 
    *MyCharacter->GetFName().ToString());
```

#### Log an FString,Int,Float

```cpp
//"%s has health %d, which is %f percent of total health"
UE_LOG(YourLog,Warning,TEXT("%s has health %d, which is %f percent of total health"),
    *MyCharacter->GetName(), MyCharacter->Health, MyCharacter->HealthPercent);
```

## Log Coloring

#### Log: Grey

```cpp
//"this is Grey Text"
UE_LOG(YourLog,Log,TEXT("This is grey text!"));
```

#### Warning: Yellow

```cpp
//"this is Yellow Text"
UE_LOG(YourLog,Warning,TEXT("This is yellow text!"));
```

#### Error: Red

```cpp
//"This is Red Text"
UE_LOG(YourLog,Error,TEXT("This is red text!"));
```

#### Fatal: Crash for Advanced Runtime Protection

You can throw a fatal error yourself if you want to make sure that certain code never runs.

I have used this myself to help protect against algorithm cases that I wanted to make sure never occurred again.

It's actually really useful!

But it does look like a crash, and so if you use this, dont be worried, just look at the crash call stack :)

* Again this is an advanced case that crashes the program, **use only for extremely important circumstances**.

```cpp
//some complicated algorithm
if(some fringe case that you want to tell yourself if the runtime execution ever reaches this point)
{
    //"This fringe case was reached! Debug this!"
    UE_LOG(YourLog,Fatal,TEXT("This fringe case was reached! Debug this!"));
}
```

## Quick tip print

This a trick for easy print debug, you can use this MACRO at the begin of your cpp

```cpp
#define print(text) if (GEngine) GEngine->AddOnScreenDebugMessage(-1, 1.5, FColor::White,text)
```

then you can use a regular lovely `print();` inside to all.

To prevent your screen from being flooded, you can change the first parameter, key, to a positive number. Any message printed with that key will remove any other messages on screen with the same key. This is great for things you want to log frequently.

## Other Options for Debugging

### Logging message to the screen

For the times when you want to just display the message on the screen, you can also do:

```cpp
 #include <EngineGlobals.h>
 #include <Runtime/Engine/Classes/Engine/Engine.h>
 // ...
 GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, TEXT("This is an on screen message!"));
 GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, FString::Printf(TEXT("Some variable values: x: %f, y: %f"), x, y));
```

To prevent your screen from being flooded, you can change the first parameter, key, to a positive number. Any message printed with that key will remove any other messages on screen with the same key. This is great for things you want to log frequently.

### Logging message to the \~ Client Console

Pressing the `~` key in Unreal brings up the client console.

If you use the `PlayerController` class you can print a message to this console, which has the advantage of being a completely different logging space which does not require tabbing out of the game to view easily

```cpp
 PC->ClientMessage("Your Message");
```

* [Answerhub post on using `ClientMessage`](https://answers.unrealengine.com/questions/81662/vshow-function.html):
* [Forum Post on post messages to the client console](https://forums.unrealengine.com/showthread.php?33367-Log-to-Console%7Csend)

## Log conventions (in the console, ini files, or environment variables)

* \[cat] = a category for the command to operate on, or 'global' for all categories.
* \[level] = verbosity level, one of: none, error, warning, display, log, verbose, all, default

At boot time, compiled in default is overridden by ini files setting, which is overridden by command line

## Log console command usage

* `Log list` - list all log categories
* `Log list [string]` - list all log categories containing a substring
* `Log reset` - reset all log categories to their boot-time default
* `Log [cat]` - toggle the display of the category \[cat]
* `Log [cat] off` - disable display of the category \[cat]
* `Log [cat] on` - resume display of the category \[cat]
* `Log [cat] [level]` - set the verbosity level of the category \[cat]
* `Log [cat] break` - toggle the debug break on display of the category \[cat]

## Log command line

* `-LogCmds=\"[arguments],[arguments]...\"` - applies a list of console commands at boot time
* `-LogCmds=\"foo verbose, bar off\"` - turns on the foo category and turns off the bar category

## Environment variables

Any command line option can be set via the environment variable **UE-CmdLineArgs**

`set UE-CmdLineArgs=\"-LogCmds=foo verbose breakon, bar off\"`

## Config file

In *DefaultEngine.ini* or *Engine.ini*:

```
[Core.Log]
global=[default verbosity for things not listed later]
[cat]=[level]
foo=verbose break
```

♥ -Rama


# Macros & Data Types


# Structs, USTRUCTS(), They're Awesome

Guide on using USTRUCTS by Rama the legend

### Overview

**Original Author: Rama**

Structs enable you to create custom variable types to organize your data, by relating other c++ or UE4 C++ data types to each other.

The power of structs is extreme organization, as well as ability to have functions for internal data type operations!

#### Technical

Structs enable you to create custom variable types to organize your data, by relating other C++ or UE4 C++ data types to each other. The power of structs is extreme organization as well as the ability to have functions for internal data type operations. '

In UE4, structs should be used for simple data type combining and data management purposes. For complex interactions with the game world, you should make a `UObject` or `AActor` subclass instead.

### Core Syntax

```cpp
//If you want this to appear in BP, make sure to use this instead //USTRUCT(BlueprintType)
USTRUCT() struct FJoyStruct
{
    GENERATED_BODY()

    // Always make USTRUCT variables into UPROPERTY()
    // any non-UPROPERTY() struct vars are not replicated

    // So to simplify your life for later debugging, always use UPROPERTY()
    UPROPERTY()
    int32 SampleInt32;

    //If you want the property to appear in BP, make sure to use this instead
    //UPROPERTY(BlueprintReadOnly)

    UPROPERTY()
    AActor* TargetActor;

    //Set
    void SetInt(const int32 NewValue)
    {
        SampleInt32 = NewValue; 
    }

    //Get
    AActor* GetActor()
    {
        return TargetActor;
    }

    //Check
    bool ActorIsValid() const
    {
        if(!TargetActor)
            return false;

        return TargetActor->IsValidLowLevel();
    }

    //Constructor
    FJoyStruct()
    {
        // Always initialize your USTRUCT variables!
        // exception is if you know the variable type has its own default 
        constructor SampleInt32 = 5;
        TargetActor = nullptr;
    } 
};
```

> **Additional Note Author: DesertEagle\_PWN**\
> The idea of USTRUCTS() is to declare engine data types that are in global scope and can be accessed by other classes/structs/blueprints. Because of this, it is invalid UE4 syntax to declare a struct inside of a class or other struct if using the USTRUCT() macro. Regular structs can still be utilized inside your classes and other structs; however these cannot be replicated natively and will not be available for UE4 reflective debugging or other engine systems such as Blueprints.
>
> **Additional Note Author: Darkgaze**\
> Concerning the variables visibility on the editor: In the example above, if you don't add "EditAnywhere" parameter into UPROPERTY inside the members of the USTRUCT, whey won't show up in the Editor panel. You will see the variable but there will be no way to see/change/unfold the values inside. The class that defines a new UPROPERTY using that struct type should have that parameter too. In case you can't modify the data and you are using blueprints, you should add BlueprintType inside the USTRUCT parenthesis.

### Examples

#### Example 1

You want to relate a float brightness value with a world space location FVector, both of which are interpolated using an Alpha value.

And you want to do this for 100 different game locations simultaneously. And you want to do this process repeatedly over time! You need to store the incremental interpolation values between game events. AActors/UObjects are not involved (You could just subclass `AActor`/`UObject` and store the data per instance)

```cpp
USTRUCT()
struct FMyInterpStruct
{
    GENERATED_BODY()

    UPROPERTY()
    float Brightness;

    UPROPERTY()
    float BrightnessGoal; //interping to

    UPROPERTY()
    FVector Location;

    UPROPERTY()
    FVector LocationGoal;

    UPROPERTY()
    float Alpha;


    void InterpInternal()
    {
        Location = FMath::Lerp<FVector>(Location,LocationGoal,Alpha);
        Brightness = FMath::Lerp<float>(Brightness,BrightnessGoal,Alpha);
    }

    //Brightness out is returned, FVector is returned by reference 
    float Interp(const float& NewAlpha, FVector& Out)
    { 
        // value received from rest of your game engine
        Alpha = NewAlpha;

        //Internal data structure management
        InterpInternal();

        //Return Values
        Out = Location;
        return Brightness;
    }

    FMyInterpStruct()
    {
        Brightness = 2;
        BrightnessGoal = 100;
        Alpha = 0;
        Location = FVector::ZeroVector;
        LocationGoal = FVector(0,0,200000);
    } 
};
```

#### Example 2

You want to track information about particle system components that you have spawned into the world through

```cpp
UGameplayStatics::SpawnEmitterAtLocation() // returns a UParticleSystemComponent
```

and you want to track the lifetime of the particle and apply parameter changes from C++. You could write your own class, but if your needs are simple or you do not have project-permissions to make a subclass of `UParticleSystemComponent`, you can just make a `USTRUCT` to relate the various data types!

```cpp
USTRUCT()
struct FParticleStruct
{
    GENERATED_BODY()

    UPROPERTY()
    UParticleSystemComponent* PSCPtr;

    UPROPERTY()
    float LifeTime;


    void SetColor()
    {
        // your code here
    }

    FLinearColor GetCurrentColor() const
    {
        // your code here
    }

    // For GC
    void Destroy()
    {
        PSCPtr = nullptr;
    }

    //Constructor
    FParticleStruct()
    {
        PSCPtr = nullptr;
        LifeTime = -1;
    }
};
```

**Particle Data Tracker**

Now you can have an array of these `USTRUCTS` for each particle that you spawn!

```cpp
// Particle Data Tracking Array
UPROPERTY()
TArray<FParticleStruct> PSCArray;
```

**Garbage Collection**

By marking a `USTRUCT` or `USTRUCT` array as `UPROPERTY()` and marking any UObject / AActor members as `UPROPERTY()`, you are protected from dangling pointer crashes

[link to article](https://app.gitbook.com/s/-M3mx7Lszp8LdwKKD7yR-887967055/wiki-archives/macros-and-data-types/How_To_Prevent_Crashes_Due_To_Dangling_Actor_Pointers)

However you must also clear ustructs you no longer need if they have pointers to `UObjects` if you ever want GC to be able garbage collect those `UObjects`.

### Structs With Struct Member Variables

The struct that wants to use another struct must be defined below the struct it wants to include.

```cpp
USTRUCT()
struct FFlowerStruct
{
    GENERATED_BODY()

    UPROPERTY()
    int32 NumPetals;

    UPROPERTY()
    FLinearColor Color;

    UPROPERTY()
    FVector Scale3D;

    void SetFlowerColor(const FLinearColor& NewColor)
    {
        Color = NewColor;
    }

    FFlowerStruct()
    {
        NumPetals = 5;
        Scale3D = FVector(1,1,1);
        Color = FLinearColor(1,0,0,1);
    }
};

USTRUCT()
struct FIslandStruct
{
    GENERATED_BODY()

    UPROPERTY()
    int32 Type;

    UPROPERTY()
    TArray<FVector> StarLocations;

    UPROPERTY()
    float RainAlpha;

    //Dynamic Array of Flower Custom USTRUCT()
    UPROPERTY() 
    TArray<FFlowerStruct> FlowersOnThisIsland;


    void SetRainAlpha(const float& NewAlpha)
    {
        RainAlpha = NewAlpha;
    }

    int32 GetStarCount() const
    {
        return StarLocations.Num();
    }

    FIslandStruct()
    {
        Type = 0;
        Percent = 1;
    }
};
```

### Struct Assignment

My personal favorite thing about structs is that unlike `UObject` or `AActor` classes, which must be utilized via pointers (`AActor*`) you can directly copy the entire contents of a `USTRUCT` to another `USTRUCT` of the same type with a single line of assignment!

```cpp
FFlowerStruct ExistingFlower;

// ... create ExistingFlower here

FFlowerStruct NewFlower;
NewFlower = ExistingFlower;
```

#### Deep Copy

If you have struct members pointing to UObjects or array pointers, you must be careful to copy these members yourself!

```cpp
USTRUCT()
struct FMyStruct
{
   int32* MyIntArray;
};

FMyStruct MyFirstStruct, MySecondStruct;

// Create the integer array on the first struct
MyFirstStruct.MyIntArray = new int32[10];
for( int i = 0; i < 10; ++i )
{
    MyFirstStruct.MyIntArray[i] = i;
}

GEngine->AddOnScreenMessage(-1, 10.f, FColor::Blue, FString::FromInt(MyFirstStruct.MyIntArray[4]));

// Assign the first struct to the second struct, i.e. create a shallow copy
MySecondStruct.MyIntArray[4] = 6;

GEngine->AddOnScreenMessage(-1, 10.f, FColor::Blue, FString::Printf(
    TEXT("%d %d"), MyFirstStruct.MyIntArray[4], MySecondStruct.MyIntArray[4]));
```

On screen the output will be

```
4
6 6
```

instead of the expected

```
4
4 6
```

This is because the data stored in `MyStruct::MyIntArray` is not actually stored inside of `MyStruct`. The new keyword creates the data somewhere in RAM and we simply store a pointer there. The address the pointer stores is copied over to `MySecondStruct`, but it still points to the same data. In fact, it would be counterproductive to remove this functionality since there are cases where you want exactly that. Additionally the Unreal Property System does not support non-UObject pointers, which is why `MyIntArray` is not marked with `UPROPERTY()`.

However, copying arrays of integers (e.g. `int32[10]` instead of `int32*`) means the data is stored directly inside the struct and as such "deep copied". However, if you store a pointer to a `UObject`, this object is NOT deep copied! Once again only the pointer is copied and the original `UObject` left unchanged. Which is good because otherwise you might manipulate the wrong instance thinking you only had one to begin with leaving the original `UObject` unaffected, thus resembling a very nerve-wrecking and very difficult to track down bug!

### Automatic Make/Break in BP

Marking the `USTRUCT` as `BlueprintType` and adding `EditAnywhere, BlueprintReadWrite, Category = "Your Category"` to `USTRUCT` properties causes UE4 to automatically create Make and Break Blueprint functions, allowing to construct or extract data from the custom `USTRUCT`.

Special thanks to Community member **Iniside** for pointing this out. :)

```cpp
USTRUCT(BlueprintType)
struct FFlowerStruct
{
    GENERATED_BODY()

    UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Flower Struct")
    int32 NumPetals;

    UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Flower Struct")
    FLinearColor Color;

    UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Flower Struct")
    FVector Scale3D;
};
```

[image (todo)](https://app.gitbook.com/s/-M3mx7Lszp8LdwKKD7yR-887967055/wiki-archives/macros-and-data-types/CustomUStructMakeBreak.jpg)

### Replication

Remember that only `UPROPERTY(`) variables of `USTRUCTS()` are considered for replication!

So if your `USTRUCT` is not replicating properly, the first thing you should check is that every member is at least `UPROPERTY()`! The struct does not have be a `BlueprintType`, it just needs `UPROPERTY()` above all properties that you want replicated.

### Other notes

In case you are looking for `GENERATED_USTRUCT_BODY`, in 4.11+, `GENERATED_BODY()` should be used instead.

### Related Links

[UStruct data member memory management](broken://pages/-M3oGdp6OytFDxuiNd7O)

### Thank You Epic for USTRUCTS()

I love `USTRUCTS()`, thank you Epic!

## Authors

Original author: Rama <3\
Captured from the epic wiki via the Wayback Machine. Reformatted by Maldonacho


# Enums For Both C++ and BP

This wiki article was written by Rama.

> This article is still in the process of being cleaned up, but it has been captured for preservation.

## Overview

Dear Community,

Here's how you can create your own Enums that can be used with C++ and BP graphs!

Enums basically give you ability to define a series of related types with long human-readible names, using a low-cost data type.

These could be AI states, object types, ammo types, weapon types, tree types, or anything really :)

![Enumgraph.jpg](https://d3ar1piqh1oeli.cloudfront.net/e/e3/Enumgraph.jpg/800px-Enumgraph.jpg)

### BP Graphs: Switch on Enum

For BP Graphs, one of the most wonderful things about ENUMS is the ability to use Switch on Enum() instead of having to do a series of branches and testing one value many times

### C++ .h File

You need to add the UENUM definition above your class and then actually create a member variable in your class that you want to have be an instance of this enum.

If you want an enum to be used in many different classes (instances of this enum in many classes) you can define the enum in some class that holds all your other important definitions like USTRUCTS().

```cpp
UENUM(BlueprintType)
enum class EVictory : uint8 {
    VE_Dance       UMETA(DisplayName="Dance"),
    VE_Rain        UMETA(DisplayName="Rain"),
    VE_Song        UMETA(DisplayName="Song"),
};
```

### Testing the Value in the C++

```cpp
UCLASS()
class YourClass : public YourSuperClass {
    GENERATED_BODY()

public:
    UPROPERTY(EditAnywhere, BlueprintReadWrite)
    EVictory VictoryEnum;

};
```

```cpp
if (EVictory == EVictory::VE_Dance) {
    EVictory = EVictory::VE_Song;
} else {
    EVictory = EVictory::VE_Rain;
};
```

### Get Name of Enum as String

```cpp
FString GetVictoryEnumAsString(EVictory::Type EnumValue) {
const UEnum* EnumPtr = FindObject<UEnum>(ANY_PACKAGE, TEXT("EVictoryEnum"), true);
    if (!EnumPtr) return FString("Invalid");
        return EnumPtr->GetNameByValue((int64)EnumValue); // for EnumValue == VE_Dance returns "VE_Dance"
    }
}
```

#### Templatized Version

```cpp
// Example usage GetEnumValueAsString<EVictoryEnum>("EVictoryEnum", VictoryEnum))); 

template<typename TEnum>
static FORCEINLINE FString GetEnumValueAsString(const FString& Name, TEnum Value) {
    const UEnum* enumPtr = FindObject<UEnum>(ANY_PACKAGE, *Name, true);
    if (!enumPtr) return FString("Invalid");
    return enumPtr->GetNameByValue((int64)Value).ToString();
} 
```

&#x20;{ return FString("Invalid"); }

```
   return enumPtr->GetNameByValue((int64)Value).ToString();
```

}

// Example usage GetEnumValueAsString\<EVictoryEnum>("EVictoryEnum", VictoryEnum))); \</syntaxhighlight>

Also, if you want to avoid retyping the enum class name as a string on every call to GetEnumValueAsString, you can also define a c++ macro in the .h file where the function is defined.

For example, if you have defined GetEnumValueAsString in a class UTextUtil in TextUtil.h, you would have this macro

\<syntaxhighlight lang="cpp">

1. define EnumToString(EnumClassName, ValueOfEnum) UTextUtil::GetEnumValueAsString\<EnumClassName>(FString(TEXT(#EnumClassName)), (ValueOfEnum))

\</syntaxhighlight>

This way in any other file where you want a FString from an enum value, you would do:

```cpp
FString EnumString = EnumToString(EVictoryEnum, EVictoryEnum::VE_Dance);
```

### GetEnumFromString

If you want to retrieve an Enum value after storing the Enum as a string, here is how!&#x20;

```cpp
template <typename EnumType>
static FORCEINLINE EnumType GetEnumValueFromString(const FString& EnumName, const FString& String) {
  UEnum* Enum = FindObject<UEnum>(ANY_PACKAGE, *EnumName, true);
  if(!Enum) { 
    return EnumType(0);
  }		
  return (EnumType)Enum->FindEnumIndex(FName(*String));
}

//Sample Usage FString ParseLine = GetEnumValueAsString<EChallenge>("EChallenge", VictoryEnumValue))); //To String EChallenge Challenge = GetEnumValueFromString<EChallenge>("EChallenge", ParseLine); //Back From String!
```

### Summary

Now you know how to make enums that are project specific, that can be used in both C++ and Blueprints!

Enjoy!

Rama


# Delegates in UE4, Raw C++, and BP Exposed

This wiki article was written by Rama.

## Overview

In this wiki I share with you the core code that you need to implement for a variety of delegates in UE4!

A delegate is basically an event that you can define and call and respond to.

Every time the event is fired off, anyone who is listening for this event will receive it and be able to take appropriate action.

In the case of **multicast** delegates, any number of entities within your code base can respond to the same event and receive the inputs and use them.

In the case of **dynamic** delegates, the delegate can be saved/loaded within a Blueprint graph (they're called Events/Event Dispatcher in BP).

For my example I will be using exclusively DYNAMIC\_MULTICAST which is the type that is most useful in Blueprints :)

### Steps

**Signature**

You create the signature of the delegate, which declares what inputs any receiving functions should specify.

```cpp
//RamaMeleeWeapon class .h

DECLARE_DYNAMIC_MULTICAST_DELEGATE_SixParams( FRamaMeleeHitSignature, class AActor*, HitActor, class UPrimitiveComponent*, HitComponent, const FVector&, ImpactPoint, const FVector&, ImpactNormal, FName, HitBoneName, const struct FHitResult&, HitResult );
```

Notice the macro declares that I will be adding 6 parameters, there are similar macros for other quantities of parameters :)

```cpp
 DECLARE_DYNAMIC_MULTICAST_DELEGATE_SixParams
```

**Calling the Delegate**

You call the delegate within the class structure where it was defined, making sure to only execute it if it is currently bound, meaning at least 1 entity is listening for this delegate / event.

**.h**

```cpp
//.h
//RamaMeleeWeapon class .h

//This should be in the class which calls the delegate, and where the signature was defined
//This is an instance of the signature that was defined above!
FRamaMeleeHitSignature RamaMeleeWeapon_OnHit;
```

**.cpp**

```cpp
//.cpp
//Only the code that is supposed to initiate the event calls Broadcast()
if(RamaMeleeWeapon_OnHit.IsBound()) //<~~~~
{
	RamaMeleeWeapon_OnHit.Broadcast(Hit.GetActor(), Hit.GetComponent(), Hit.ImpactPoint, Hit.ImpactNormal, Hit.BoneName, Hit);
}
```

Comment from [Darkgaze](file:///index.php?title=User:Darkgaze\&action=edit\&redlink=1): As the official [Multicast docs](https://docs.unrealengine.com/latest/INT/Programming/UnrealArchitecture/Delegates/Multicast/index.html) say:

(...)It is always safe to call Broadcast() on a multi-cast delegate, even if nothing is bound. The only time you need to be careful is if you are using a delegate to initialize output variables, which is generally very bad to do.(...)

So calling InBound() is not necessary. Only in Single-cast delegates.

**Responding to the Delegate**

Anywhere you want, you can declare functions which receive the parameters by type and name specified in the delegate signature.

```cpp
//Any class can add a function that uses the delegate signature and responds to the Broadcast() event 
UFUNCTION()
void RespondToMeleeDamageTaken(AActor* HitActor, UPrimitiveComponent* HitComponent, const FVector& ImpactPoint, const FVector& ImpactNormal, FName HitBoneName, const FHitResult& HitResult)
```

See below to learn how to bind the delegate instance to this function or any number of functions that are present in class instances anywhere in your code base!

### UFUNCTION()  !

Please note that functions that are responding to delegate broadcasts should be UFUNCTION()!

If your delegate Broadcast stalls the game for a bit and then doesnt work, it's because you did not make one of your receiving functions a UFUNCTION()

<3 Rama

### Binding To The Delegate

#### Dynamic Delegates

```cpp
RamaMeleeWeaponComp->RamaMeleeWeapon_OnHit.AddDynamic(this, &USomeClass::RespondToMeleeDamageTaken); //see above in wiki
```

#### Multicast Delegates

Binding to non-dynamic requires this syntax:

```cpp
RamaMeleeWeaponComp->RamaMeleeWeapon_OnHit.AddUObject(this, &USomeClass::RespondToMeleeDamageTaken); //see above in wiki
```

<https://docs.unrealengine.com/en-us/Programming/UnrealArchitecture/Delegates/Multicast>

#### Non Multicast

Binding a UObject to a non-dynamic, non-multicast delegate requires you to use the following syntax.

```cpp
//in some class cpp file

RamaMeleeWeaponComp->RamaMeleeWeapon_OnHit.BindUObject(this, &USomeClass::RespondToMeleeDamageTaken); //see above in wiki
```

You need to access the delegate where it is stored, in my case this is the RamaMeleeWeaponComponent

The idea is you are telling the delegate instance that it is getting a new binding, to this SomeClass insance, which is why you include the this pointer.

So this code appears where you want to add the binding to the event/delegate, but it must refer to the one signature instance present in the original class instance.

So basically this delegate binding is **an agreement between two instances**, where one instance is of the class that declares and implements the delegate, and the other instance is any ole' class that has declared the function signature to match the delegate signature.

There's nothing abstract here, everything is instances, so you must bind your object instance to the delegate signature instance that is part of the instance of the class that is going to fire off the broadcasting.

This is why I have a pointer to RamaMeleeWeaponComp->RamaMeleeWeapon\_OnHit, and I am **also** including the this pointer so that the signature knows about the calling object instance.

The reason it is a this pointer is because the code above is run in the object that wants to bind to the delegate, so this is a self-referencing pointer to the UObject we are binding to the delegate.

### Raw C++ Class Instances

Raw delegates are used with non UObject classes, like plugin modules.

```cpp
RamaMeleeWeaponComp->RamaMeleeWeapon_OnHit.BindRaw(this, &FSomeRawCPPClass::RespondToMeleeDamageTaken);
```

### Slate Class Instances

Slate delegates use this syntax:

```cpp
RamaMeleeWeaponComp->RamaMeleeWeapon_OnHit.CreateSP(this, &SSomeSlateClass::RespondToMeleeDamageTaken);
```

### Binding is Per-Instance

Please note that when you bind to the delegate this is a per-instance process! That is why you need to include the this pointer, because whichever instance you are calling the code in, it is that particular instance whose function will get called when the delegate is broadcasted.

This means you can choose to have only certain instances of a uobject respond to a delegate, or choose to bind or unbind at any time!

### BP-Friendly Delegates

A BP friendly delegate requires this additional .h code to expose the delegate to Blueprints.

```cpp
//RamaMeleeWeapon.h

UPROPERTY(BlueprintAssignable, Category="Rama Melee Weapon")
FRamaMeleeHitSignature RamaMeleeWeapon_OnHit;
```

BP-friendly Delegates should be DYNAMIC\_MULTICAST so they can be serialized (saved/loaded) with the BP graph.

### Level Blueprint Friendly Delegates

When you've made BP-friendly delegates on objects that you can place in the level, you can simply right click on the object instance in your level -> Add Event and see your new delegate! So nice!

This is an additional benefit of using DYNAMIC\_MULTICAST delegates! Multi-cast implies binding multiple of various object instances to the delegate and then firing off the event to everyone from a single .Broadcast, which can include your Level Blueprint as a recipient/listener!

### Video Example

Here is a video on how a C++ delegate created in an actor component in C++ looks and is called in Blueprints!

The code in this wiki and this video are from my [Melee Weapon Plugin](http://ue4code.com/melee_weapon_system_plugin_per_bone_collision_accuracy)

<http://www.youtube.com/watch?v=aufEB4TCf30&t=5m24s>

### Further Reading

Epic Documentation: <https://docs.unrealengine.com/latest/INT/Programming/UnrealArchitecture/Delegates/>

### DYNAMIC\_MULTICAST And Other Types

There are other delegate types besides DYNAMIC\_MULTICAST that are not quite as versatile when it comes to Blueprints.

Check out the source code of Delegate.h:`Runtime/Core/Public/Delegates/Delegate.h`

For a detailed explanation!

Sample from this file:

```
**
 *  C++ DELEGATES
 *  -----------------------------------------------------------------------------------------------
 *
 *	This system allows you to call member functions on C++ objects in a generic, yet type-safe way.
 *  Using delegates, you can dynamically bind to a member function of an arbitrary object,
 *	then call functions on the object, even if the caller doesn't know the object's type.
 *
 *	The system predefines various combinations of generic function signatures with which you can
 *	declare a delegate type from, filling in the type names for return value and parameters with
 *	whichever types you need.
 *
 *	Both single-cast and multi-cast delegates are supported, as well as "dynamic" delegates which
 *	can be safely serialized to disk.  Additionally, delegates may define "payload" data which
 *	will stored and passed directly to bound functions.
```

### Conclusion

Enjoy using delegates in UE4 so that any part of your code base can respond to an event triggered by one section of your code!

Also enjoy exposing delegates via C++ for the rest of your team to use in Blueprints!

Enjoooy!

♥

Rama


# Interfaces in C++

This wiki article was originally written by Rama and received contributions from HuntaKiller, DarkGaze, and Ruhrpottpatiot.

## Overview

Here's a tutorial on using **UE4 C++ Interfaces in 4.11+**

Interfaces allow different objects to share common functions, but allow objects to handle that function differently if it needs to. Any classes that use an interface must implement the functions that are associated with that interface.

This gives you a lot of power over your game actors, allowing you to trigger events both in C++ and in blueprints that your game actors can handle differently.

For example, the interface implemented in this tutorial enables you to have an interface like TimeBasedBehaviour, which has a function ReactToHighNoon, and have a bunch of actors respond to this event differently, each with their own behaviour.

Flower actors that implement this interface could override the ReactToHighNoon method to open blossoms completely Frog actors implementing it could override ReactToHighNoon to hide under rocks, for example

You can then have an event, SunReachedHighNoon that is triggered anywhere (such as the level blueprint, in an actor, or a static blueprint library) which can take any actor, check if it implements the interface, and if it does it can call any of the functions of that interface and the actor will act according to how that specific actor has the behaviours defined.

This means you can trigger events anywhere and as long as you have a pointer to your actor, you can ask it to do specific things without needing to know its types because you can **easily determine whether any given actor has an interface or not by casting an actor to that interface**. If the cast succeeds then the actor does implement the given interface, and you can call functions using that interface.

We will implement two interface functions: one which forces you to implement default C++ behaviour on any class which uses the interface, a **BlueprintNativeEvent** called ReactToHighNoon(), and one **BlueprintImplementableEvent** which does not force you to define default C++ behaviour, called ReactToMidnight().

### Creating The Interface

The following is an example implementation of a ReactsToTimeOfDay interface.

When following this tutorial and creating your interface, you'd replace ReactToHighNoon() with your function you want to force default behaviour, and ReactToMidnight() with your function that has no default behaviour.

(If you wish the function to be treated as an event, then it must return void. If you wish the function to be able to be overridden in the BP editor, then it must have a non-void return type. Replace the return type of the function with a string or void if you want to perform a simplistic test. The reasoning is discussed further below in the Critical To Note section)

#### ReactsToTimeOfDay.h

```cpp
#pragma once

#include "ReactsToTimeOfDay.generated.h"

/**
 * Must have BlueprintType as a specifier to have this interface exposed to blueprints.
 * With this line you can easily add this interface to any blueprint class.
 */
UINTERFACE(BlueprintType)
class MYPROJECT_API UReactsToTimeOfDay : public UInterface {
  GENERATED_UINTERFACE_BODY()
};

class MYPROJECT_API IReactsToTimeOfDay {
  GENERATED_IINTERFACE_BODY()

public:

  // classes using this interface must implement ReactToHighNoon
  UFUNCTION(BlueprintNativeEvent, BlueprintCallable, Category = "MyCategory")
  bool ReactToHighNoon();

  //classes using this interface may implement ReactToMidnight
  UFUNCTION(BlueprintImplementableEvent, BlueprintCallable, Category = "MyCategory")
  bool ReactToMidnight();

};
```

> **Note checked for 4.18+:** `GENERATED_UINTERFACE_BODY()` and `GENERATED_IINTERFACE_BODY()`, can be now changed to `GENERATED_BODY()`, which is an updated version of those two that works for structs, etc, but errors could be a little confusing if you get compile errors since there's no way to differentiate. You could create an automatic interface to see how it looks now using Create C++ Class context menu on the content editor and choosing Interface type.

#### ReactsToTimeOfDay.cpp

```cpp
#include "MyProject.h"
#include "ReactsToTimeOfDay.h"

UReactsToTimeOfDay::UReactsToTimeOfDay(const class FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) {
  // add your code here
}
```

### Using An Interface With C++ Classes

You have to use **multiple inheritance**, and inherit from the IReactsToTimeOfDay class we created.

The first inherited class will be the base class of your actor, anything you want, a ASkeletalMeshActor is used here as an example.

#### Flower.h

```cpp
#include "ReactsToTimeOfDay.h"
#include "ASkeletalMeshActor.generated.h"

// ...other includes may appear here depending on your class

UCLASS()
class AFlower : public ASkeletalMeshActor, public IReactsToTimeOfDay {
  GENERATED_BODY()

public:

  /* ... other AFlower properties and functions declared ... */

  UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category = "MyCategory")
  bool ReactToHighNoon(); virtual bool ReactToHighNoon_Implementation() override;

};
```

`virtual bool ReactToHighNoon_Implementation() override;`

This line tells your class that it has a function of this name and signature to inherit from the interface, which is how calls to the interface functions are able to interact with this class.

`UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category = "MyCategory") bool ReactToHighNoon();`&#x20;

This tells your class that you can both call and override this function in blueprints. You need this part as well if you want to be able to override C++ functionality within BP, as BlueprintNativeEvents are intended to be used.

Notice that `ReactToMidnight()`, the BlueprintImplementableEvent, is not defined here. A BlueprintImplementableEvent is declared (its existance) in our interface, but defined (its behaviour) in blueprints only.

#### Flower.cpp

```cpp
// other flower.cpp code

bool AFlower::ReactToHighNoon_Implementation() {
 // Default behaviour for how flower would react at noon //OpenPetals(); //AcceptBugs(); //...
 return true;
} 
```

Any number of classes and subclasses can implement this interface using this format

#### Frog.h

```cpp
#include "ReactsToTimeOfDay.h"
#include "AFrog.generated.h"

UCLASS()
class AFrog : public ACharacter, public IReactsToTimeOfDay {
  GENERATED_BODY()
  
  /* ... other AFrog properties and functions declared ... */

  UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category = "MyCategory")
  bool ReactToHighNoon(); virtual bool ReactToHighNoon_Implementation() override;
  
};
```

#### Frog.cpp

```cpp
// other Frog code

bool AFrog::ReactToHighNoon_Implementation() {
  // Default behaviour for how a frog would react at noon //GoSwim(); //...
  return true;
}
```

#### Determining If a Given Actor Has The Interface

To determine if an actor implements an interface in C++, simply cast your class to the interface, if it returns NULL then the object is not using it. If it is successful, you can use that pointer cast to the interface to call your function, which will execute from the proper class.

```cpp
// Example: somewhere else in code we are trying to see if our object reacts to time of day
// Some pointer is defined to any class inheriting from UObject UObject* pointerToAnyUObject;

IReactsToTimeOfDay* TheInterface = Cast<IReactsToTimeOfDay>(pointerToAnyUObject);
if (TheInterface) {
  // Don't call your functions directly, use the 'Execute_' prefix //the Execute_ReactToHighNoon
  // and Execute_ReactToMidnight are generated on compile //you may need to compile before these
  // functions will appear TheInterface->Execute_ReactToHighNoon (pointerToAnyUObject);
  TheInterface->Execute_ReactToMidnight (pointerToAnyUObject);
}

//end of code segment
```

&#x20;**Critical To Note**

* &#x20;Whenever calling your interface functions in C++, never call the direct functions, always use the one with the Execute\_ prefix
* &#x20;Although it might seem, that you function must return a value to be properly implemented, this is not true. If your interface doesn't return a value UE4 treats it as an event. At first glance this might seem as an error, but this is not the case. You just have to create the implementation details in the event graph instead of overriding. You still can call the function normally via function, or interface call. --Ruhrpottpatiot
* &#x20;To determine if an actor implements an interface in both C++ and Blueprints use

```cpp
if (pointerToAnyUObject->GetClass()->ImplementsInterface(UReactsToTimeOfDay::StaticClass())) {
    IReactsToTimeOfDay::Execute_ReactToHighNoon(pointerToAnyUObject);
}
```

#### The Magic Interfaces

```cpp
TheInterface->Execute_ReactToHighNoon();
```

From the above code you can see that the function is being called off of the interface, you never even need to know what type of object you're dealing with, just whether it supports the interface you need.

It produces different results depending on the actual class it is, calling the overridden function. This is called polymorphism.

### Overriding Behaviour In Blueprints

Once this is all implemented, the classes that you have set up with the interface in C++ will have its interface functions appear with the blueprint's variables and other functions.

[![InterfaceBP1.png](https://web.archive.org/web/20181002150134im_/https://d26ilriwvtzlb.cloudfront.net/7/7b/InterfaceBP1.png)](https://web.archive.org/web/20181002150134/https://wiki.unrealengine.com/index.php?title=File:InterfaceBP1.png)

[![InterfaceBP2.png](https://web.archive.org/web/20181002150134im_/https://d26ilriwvtzlb.cloudfront.net/6/6a/InterfaceBP2.png)](https://web.archive.org/web/20181002150134/https://wiki.unrealengine.com/index.php?title=File:InterfaceBP2.png)

\
&#x20;Again, your function **must** have a return value for it to appear in this list, otherwise it is considered an event and cannot be overridden as a function. You can however use the event from the interface in blueprint's event graph and override it that way.

### Summary

You can trigger global events that only certain actors will respond to each actor can respond to an event in their own unique way.&#x20;

While it's a little bit more complicated of a setup it helps keeping the code very simple and is much more performance friendly than casting to multiple different types of classes!


# Iterators

Object & Actor Iterators, Optional Class Scope For Faster Search

### Overview

Dear Community,

In the UE4 engine two of the most powerful tools I use constantly are the Object and the Actor Iterators.

You can use these functions to search for all Run-Time instances of actors and objects, or only specific classes!

**The advantage of using the UE4 iterators is that they are always accurate!**

You dont have to maintain dynamic arrays of actors, and then remember to remove actors when they are destroyed!

The Actor and Object Iterators always give you the real and accurate list of all actors / objects currently still active in your game world

Yay!

#### Include

**#include "EngineUtils.h"**

**Controller Class**

You dont have to use these functions in the Controller Class,

I was just doing this for the sake of ClientMessage and easy testing on your part :)

### Object Iterator

```cpp
void AYourControllerClass::PrintAllObjectsNamesAndClasses()
{
    for ( TObjectIterator<UObject> Itr; Itr; ++Itr )
    {
        ClientMessage(Itr->GetName());
        ClientMessage(Itr->GetClass()->GetDesc());
    }
}
```

### Actor Iterator

```cpp
void AYourControllerClass::PrintAllActorsLocations()
{
    //EngineUtils.h
    for (TActorIterator<AActor> ActorItr(GetWorld()); ActorItr; ++ActorItr )
    {
        ClientMessage(ActorItr->GetName());
        ClientMessage(ActorItr->GetActorLocation().ToString());
    }
}
```

### Object Iterator & Actor Iterator Comparison

#### Disadvantage of Object Iterator

Unlike the Actor Iterator, the Object iterator is going to iterate over objects in the Pre-PIE world / the Editor World.

This can lead to unexpected results.

This is not an issue if you are running your game as an independent Game Instance / the editor is closed :)

#### Critical Advantage of Object Iterator

A critically important advantage of the Object Iterator is that it does not require a UWorld\* Context!

Notice how all the uses of Actor Iterator involve GetWorld()

```cpp
TActorIterator ActorItr<AStaticMeshActor>(GetWorld());
```

If you need to find an object in the game world from a static context, where you cannot obtain the UWorld via some other means,

then the Object Iterator is the way to get the proper context and access the entire living game world!

#### Object Iterator Can Search for AActors

Because AActor extends UObject, the Object Iterator can search for AActors!

But the AActor Iterator cannot search for instances of UObjects that do not extend AActor at some point.

So the Object Iterator can do a search for all UStaticMeshComponents, as well as all ACharacters!

```cpp
TObjectIterator<UStaticMeshComponent> Itr;
```

```cpp
TObjectIterator<ACharacter> Itr;
```

### Specifying Classes & Subclasses To Search For

Perhaps the most powerful feature of the Actor and Object Iterators is the ability to limit the scope of the search to a chosen base class and its subclasses!

This makes the iterator run faster and helps you gather only the data you really want from the game world!

#### Object Iterator, Specific Base Class

```cpp
void AYourControllerClass::PrintAllSkeletalMeshComponentsNames()
{
    for ( TObjectIterator<USkeletalMeshComponent> Itr; Itr; ++Itr )
    {
        ClientMessage(Itr->GetName());
    }
}
```

#### Actor Iterator, Specific Base Class

```cpp
void AYourControllerClass::PrintAllStaticMeshActorsLocations()
{
    //EngineUtils.h
    for (TActorIterator<AStaticMeshActor> ActorItr(GetWorld()); ActorItr; ++ActorItr)
    {
        ClientMessage(ActorItr->GetName());
        ClientMessage(ActorItr->GetActorLocation().ToString());
    }
}
```

### Using a World-Filter with ObjectIterator

ObjectIterator can and will return editor-instance / default object objects that simply should not be edited at runtime!

To filter out objects that you should not be editing at runtime, you can do a world check with an object that you know is part of the correct world (not the editor world)!

```cpp
UWorld* YourGameWorld = //set this somehow, from another UObject or pass it in as parameter

for(TObjectIterator<UYourObject> Itr; Itr; ++Itr)
{
   //World Check
   if(Itr->GetWorld() != YourGameWorld)
   {
      continue;
   }
   //now do stuff
}
```

#### In-Engine Example \~ Get All Widgets Of Class

The above is the code structure that I used for my Get All Widgets of Class node, pull request that Epic accepted that is now live in 4.7 !

**Github Link**

<https://github.com/EpicGames/UnrealEngine/pull/569>

I avoid getting the UMG widget default objects /editor objects by passing in the world using the Blueprint method of setting a WorldContextObject!

Enjoy!

## Authors

Original author: Rama <3

Ported from wiki by Firefly74940


# String Conversions: FString to FName, FString to Int32, Float to FString

Guide on String conversions (from/to) by Rama the legend

**Content**

* [Overview](/wiki-archives/macros-and-data-types/string-conversions#overview)
  * [Converting FString to FNames](/wiki-archives/macros-and-data-types/string-conversions#converting-fstring-to-fnames)
  * [std::string to FString](/wiki-archives/macros-and-data-types/string-conversions#std--string-to-fstring)
  * [FString to std::string](/wiki-archives/macros-and-data-types/string-conversions#fstring-to-std--string)
* [FCString Overview](/wiki-archives/macros-and-data-types/string-conversions#fcstring-overview)
  * [Converting FString to Numbers](/wiki-archives/macros-and-data-types/string-conversions#converting-fstring-to-numbers)
  * [FString to Integer](/wiki-archives/macros-and-data-types/string-conversions#fstring-to-integer)
  * [FString to Float](/wiki-archives/macros-and-data-types/string-conversions#fstring-to-float)
* [Float/Integer to FString](/wiki-archives/macros-and-data-types/string-conversions#float-integer-to-fstring)
* [UE4 Source Header References](/wiki-archives/macros-and-data-types/string-conversions#ue4-source-header-references)
* [Optimization Issues Concerning FNames](/wiki-archives/macros-and-data-types/string-conversions#optimization-issues-concerning-fnames)

## Overview

**Original Author: Rama**

Below are conversions for the following types: 1. FString to FName 2. std::string to FString 3. FString and FCString Overview 4. FString to Integer 5. FString to Float 6. Float/Integer to FString 7. UE4 C++ Source Header References 8. Optimization Issues Concerning FNames

All the header files I refer to in this tutorial are found in

```
your UE4 install directory  / Engine / Source
```

you will probably want to do a search for them from this point :)

### Converting FString to FNames

Say we have

```cpp
FString TheString = "UE4_C++_IS_Awesome";
```

To convert this to an FName you do:

```cpp
FName ConvertedFString = FName(*TheString);
```

### std::string to FString

```cpp
#include <string>
//....
std::string TestString = "Happy"; 
FString HappyString(TestString.c_str());
```

### FString to std::string

```cpp
#include <string>
//....
FString UE4Str = "Flowers";
std::string MyStdString(TCHAR_TO_UTF8(*UE4Str));
```

You will find this particularly useful in cases other than float and int32! C++ std::String::to\_string <http://en.cppreference.com/w/cpp/string/basic_string/to_string>

## FCString Overview

### Converting FString to Numbers

The *operator on FStrings returns their TCHAR* data which is what FCString functions use. If you cant find the function you want in FStrings (UnrealString.h) then you should check out the FCString functions (CString.h) I show how to convert from FString to FCString below: Say we have

```cpp
FString TheString = "123.021";
```

### FString to Integer

(note Atoi is unsafe; no way to indicate errors)

```cpp
int32 MyShinyNewInt = FCString::Atoi(*TheString);
```

### FString to Float

```cpp
float MyShinyNewFloat = FCString::Atof(*TheString);
```

Note that Atoi and Atof are static functions, so you use the syntax FCString::TheFunction to call it :)

## Float/Integer to FString

```cpp
FString NewString = FString::FromInt(YourInt);
FString VeryCleanString = FString::SanitizeFloat(YourFloat);
```

Static functions in the UnrealString.h :)

## UE4 Source Header References

```cpp
CString.h
UnrealString.h
NameTypes.h
```

See CString.h for more details and other functions like

```cpp
atoi64 (string to int64)
Atod    (string to double precision float)
```

For a great deal of helpful functions you will also want to look at UnrealString.h for direct manipulation of FStrings!

## Optimization Issues Concerning FNames

FNames are inherently fast, but you could be forcing a hashmap lookup if you are accessing them in the wrong way. Look at the following code:

```cpp
if (ActorHasTag(TEXT("MyFNameActor_Tag")))
```

This code will take the character string "MyFNameActor\_Tag" and then look it up in the FName hashmap. Whereas this code doesn't need to do a string conversion:

```cpp
static const FName NAME_MyFNameActor(TEXT("MyFNameActor_Tag"));
if (ActorHasTag(NAME_MyFNameActor))
```

In our testing with UE4 4.14, the second method is nearly 100 times faster than using the string lookup. So please, always use the static const FName method over the TEXT() method. For more info on FNames check out

```cpp
NameTypes.h
```

Enjoy!

## Authors

Original author: Rama <3\
Minor Authors: Kory\
Captured from the epic wiki via the Wayback Machine. Reformatted by DarioMazzanti


# Networking


# Standalone Dedicated Server

This guide shows you how to package and compile your game as a standalone dedicated server for both Windows and Linux.

## Standalone Dedicated Server

*This is currently only possible using an engine compiled from source. It is not possible through an engine installed via the Epic Launcher. This was deemed necessary due to the increase in size that would occur if the required files were included in the installed version of the engine.*

### Packaging the Content

The dedicated server needs packaged content. Go to File -> Package Project -> Packaging Settings. Here you have a few options:

* Use Pak File: Pack all the assets into one .pak file - disable if you want to have the regular content structure (e.g. for incremental uploads)
* Full Rebuild: You might want to disable this to lower packaging times

  Then go to File -> Package Project -> Package Windows/Linux and select an output directory. The engine will now package the content and compile the standalone client code - this may take some time in case of a full rebuild.

### Compiling the Server

#### Linux Compiler Toolchain

Linux compilation is currently only supported on Windows using a cross-compilation toolchain based on Clang. A precompiled toolchain from Epic is available here: <https://github.com/EpicGames/UnrealEngine/releases/tag/4.1.0-release>. After you unzipped the toolchain, make sure to add the environment variable LINUX\_ROOT and set it to the location of the toolchain (see README.md for details).

#### Compilation

The next step is to compile the server code using Visual Studio. First, you need to set up a special server target for UnrealBuildTool.

You can use the following template:

```cpp
// Copyright 1998-2014 Epic Games, Inc. All Rights Reserved.

using UnrealBuildTool;
using System.Collections.Generic;

public class GameServerTarget : TargetRules
{
    public GameServerTarget(TargetInfo Target)
    {
        Type = TargetType.Server;
    }

    //
    // TargetRules interface.
    //
    public override void SetupBinaries(
        TargetInfo Target,
        ref List<UEBuildBinaryConfiguration> OutBuildBinaryConfigurations,
        ref List<string> OutExtraModuleNames
        )
    {
        base.SetupBinaries(Target, ref OutBuildBinaryConfigurations, ref OutExtraModuleNames);
        OutExtraModuleNames.Add("Game");
    }

    public override bool GetSupportedPlatforms(ref List<UnrealTargetPlatform> OutPlatforms)
    {
        // It is valid for only server platforms
        return UnrealBuildTool.UnrealBuildTool.GetAllServerPlatforms(ref OutPlatforms, false);
    }

    public override List<UnrealTargetPlatform> GUBP_GetPlatforms_MonolithicOnly(UnrealTargetPlatform HostPlatform)
    {
        if (HostPlatform == UnrealTargetPlatform.Mac)
        {
            return new List<UnrealTargetPlatform>();
        }
        return new List<UnrealTargetPlatform> { HostPlatform, UnrealTargetPlatform.Win32, UnrealTargetPlatform.Linux };
    }

    public override List<UnrealTargetConfiguration> GUBP_GetConfigs_MonolithicOnly(UnrealTargetPlatform HostPlatform, UnrealTargetPlatform Platform)
    {
        return new List<UnrealTargetConfiguration> { UnrealTargetConfiguration.Development };
    }
}
```

Just replace all instances of "Game" with the name of your game project.

Its possible that there are no functions to override by the overrides so it will not build. Throw these out aswell if there are problems.

Save it as `<Game>Server.Target.cs` next to the other target files and regenerate the project files.

Open Visual Studio, set the configuration to \*Server and select the platform target accordingly.

Now it's time to build your game project. Using the above UBT target, the executable will end up in `<game>/Binaries/<platform>/<Game>Server`. Move the executable over to `<cooked>/<platform>/<game>/binaries/<platform>`.

### Platform Specifics

#### Windows

Simply execute `<Game>Server.exe`. If you want a log window, start with `-log`.

#### Linux

The server will listen for UDP packets on port 7777 by default, so make sure to open this port in your firewall.

With some Unreal Engine releases (4.2 and below) you can run into this message if you don't pass -pak:

```
Could not adjust number of file handles, consider changing "nofile" in /etc/security/limits.conf and relogin.
```

The solution is to pass -pak on the command line when starting the server.

## Authors

Original author: **Epic Games**\
Captured from the epic wiki via the Wayback Machine. Reformatted by Maldonacho


# How To Use Sessions In C++

## Features for the future

* &#x20;Example of network error handling. Like getting disconnected due to a server shutdown.
* &#x20;Example of getting information into UMG. Like the Serverlist.
* &#x20;Example of extending the GameSession class. Adding more information to your GameSession.
* &#x20;Example of extending several other classes that you can make your Session System unique and you will directly understand the ShooterGame after learning all of this.

## What is this Tutorial about?

In this Tutorial, I'm going to show you a very basic Code to Create, Find, Join and Destroy Session in C++. So basically we are going to create the Blueprint Session Nodes.

## Getting Started

### Prepare your Project to use Sessions and OnlineSubsystems

So first of all, we need to get your Project ready to use all of this. I recommend you to start with an empty project, so you can first get an idea how this works, before trying to implement this into your already started project!

#### Changing the "DefaultEngine.ini"

You can find the "DefaultEngine.ini" file in the Config folder in your top most project folder. You will want to add the following line to it:

```
[OnlineSubsystem]
DefaultPlatformService=Null
```

#### Changing the "YourProjectName.Build.cs"

You can find this file in your Project when you opened it with Visual Studio. You need to add "OnlineSubsystem", "OnlineSubsystemUtils" (for later usage) and the OnlineSubsystem NULL. It should look similar to this:

```csharp
using UnrealBuildTool;

public class NetworkSessionTest : ModuleRules
{
    public NetworkSessionTest(TargetInfo Target)
    {
         PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore", "OnlineSubsystem", "OnlineSubsystemUtils" });

         DynamicallyLoadedModuleNames.Add("OnlineSubsystemNull");
    }
}
```

#### Changing the "YourProjectName.h"

This file can also be found in the Project when you open it with Visual Studio. You want to change

```cpp
#include "EngineMinimal.h" 
```

to

```cpp
#include "Engine.h".
```

As well as add these two #includes under the "Engine.h" one.

```cpp
#include "UnrealNetwork.h"
#include "Online.h"
```

So your file looks something like this:

```cpp
#ifndef __NETWORKSESSIONTEST_H__
#define __NETWORKSESSIONTEST_H__

#include "Engine.h"
#include "UnrealNetwork.h"
#include "Online.h"
#endif
```

And that's it for setting up the Project!

### My TestProject Setup

So, i want to let you know how my test project is setup and what i am using. I create a new fresh C++ Thirst Person Project and added **ONE** Class.

I made a child class of "UGameInstance" and called it "UNWGameInstance". (NW = Network). This is what i am referring to from now on and what you will read when seeing my function. Because every function for Creating, Finding,.. Sessions will be placed here.

## Code to Create, Find, Join and Destroy Sessions

We are using a lot of Unreal Engine 4's functions here. All these functions are placed in an "SessionInterface" that is designed to handle sessions for different OnlineSubsystems. So although we are using "NULL" here, this should also work with Steam and other Subsystems. At least for the basics that all Subsystems share.

These functions all call a so called "delegate" once they are finished doing what they should do. All Session actions can take some time, so these functions are important. We will create 1-2 delegates, handles and functions for every one of these 4 Sessions operations. They will give us information like if the action was successful or not.

#### Terms you will read a lot about

| Word/Term         | Explanation                                                                                                                                                                                                                                                                                                                                             |
| ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| OnlineSubsystem   | OnlineSubsystems are for example "Steam". But you can also use "NULL", which is simply the basic UE4 Subsystem. They all use so called "Wrapper"-Functions. They give us Friend Lists, Unique IDs or Master Server that allow us to find Servers over the Internet and not only on LAN!                                                                 |
| Wrapper Functions | Wrapper Functions are something really cool that makes it easy for us to setup the Sessions for all different OnlineSubsystems. While we only need to call "CreateSession", this wrapper function will do the necessary steps to Create a Session in the active Subsystem. So we can create our logic without thinking about Steam or other Subsystems. |
| Session           | A Session is not the Map or the Server itself. A Session is an invisible thing that a Server can Create and a Client can join. They will still need to join the specific Map after joining the Session. A Session is more like an entry in a Database that helps you keeping track of all running Servers.                                              |
| Session Interface | That is nearly the same as the Session explained above. We will use the Interface instead of the Session itself, because it uses the Wrapper functions we need. We can always get this Internet if we have a valid OnlineSubsystem!                                                                                                                     |

### Creating a Session

Yes, let's start with creating a simple Session. I will always post the things we put into the Header file first and after that the logic will fill in with the .cpp File! This will all be placed in the UGameInstance Child class i have created. We don't need other classes.

**So what do we need?**

**Creating a Session | Header File**

First we need a function we can use to gather all the settings we want to use for our Session. Let's call this function "HostSession".

```cpp
In our UNWGameInstance.h:

/**
*	Function to host a game!
*
*	@Param		UserID			User that started the request
*	@Param		SessionName		Name of the Session
*	@Param		bIsLAN			Is this is LAN Game?
*	@Param		bIsPresence		"Is the Session to create a presence Session"
*	@Param		MaxNumPlayers	        Number of Maximum allowed players on this "Session" (Server)
*/
bool HostSession(TSharedPtr<const FUniqueNetId> UserId, FName SessionName, bool bIsLAN, bool bIsPresence, int32 MaxNumPlayers);
```

The comments explain a lot already, so i will step back from explaining the parameters in the function declarations.

Now we also need the Delegates i talked about earlier. They are used by the "CreateSession" function of the SessionInterface to tell use when the process is done.

```cpp
// In our UNWGameInstance.h:

/* Delegate called when session created */
FOnCreateSessionCompleteDelegate OnCreateSessionCompleteDelegate;
/* Delegate called when session started */
FOnStartSessionCompleteDelegate OnStartSessionCompleteDelegate;

/** Handles to registered delegates for creating/starting a session */
FDelegateHandle OnCreateSessionCompleteDelegateHandle;
FDelegateHandle OnStartSessionCompleteDelegateHandle;
```

So we have a Delegate and a Handle for Creating and Starting a Session. Now we also need a variable we use for the Settings that our Session will have (like LAN or Number of allowed Players):

```cpp
// In our UNWGameInstance.h:

TSharedPtr<class FOnlineSessionSettings> SessionSettings;
```

And we will also add a Constructor to our GameInstance class, which is called when the Object is created. We need this to bind the functions to the delegates!

```cpp
// In our UNWGameInstance.h

UNWGameInstance(const FObjectInitializer& ObjectInitializer);
```

And finally, we need a function that we bind to the Delegate, so we can perform some actions once we know that the Creation process is complete:

```cpp
// In our UNWGameInstance.h:

/**
*	Function fired when a session create request has completed
*
*	@param SessionName the name of the session this callback is for
*	@param bWasSuccessful true if the async action completed without error, false if there was an error
*/
virtual void OnCreateSessionComplete(FName SessionName, bool bWasSuccessful);

/**
*	Function fired when a session start request has completed
*
*	@param SessionName the name of the session this callback is for
*	@param bWasSuccessful true if the async action completed without error, false if there was an error
*/
void OnStartOnlineGameComplete(FName SessionName, bool bWasSuccessful);
```

Again, the Comments explain the parameters. These function will have different values for their parameters depending on if the process was successful or not!

**Creating a Session | CPP file**

Now we fill these functions with logic.

First of all, we will bind the functions to the delegates in our Constructor:

```cpp
// In our UNWGameIntance.cpp:

UNWGameInstance::UNWGameInstance(const FObjectInitializer& ObjectInitializer)
	: Super(ObjectInitializer)
{
	/** Bind function for CREATING a Session */
	OnCreateSessionCompleteDelegate = FOnCreateSessionCompleteDelegate::CreateUObject(this, &UNWGameInstance::OnCreateSessionComplete);
	OnStartSessionCompleteDelegate = FOnStartSessionCompleteDelegate::CreateUObject(this, &UNWGameInstance::OnStartOnlineGameComplete);
}
```

All upcoming bindings for the other operations will be placed in this Constructor, under these two binds.

Now let's have a look at the "HostSession" function we created:

```cpp
// In our UNWGameIntance.cpp:

bool UNWGameInstance::HostSession(TSharedPtr<const FUniqueNetId> UserId, FName SessionName, bool bIsLAN, bool bIsPresence, int32 MaxNumPlayers)
{
	// Get the Online Subsystem to work with
	IOnlineSubsystem* const OnlineSub = IOnlineSubsystem::Get();

	if (OnlineSub)
	{
		// Get the Session Interface, so we can call the "CreateSession" function on it
		IOnlineSessionPtr Sessions = OnlineSub->GetSessionInterface();

		if (Sessions.IsValid() && UserId.IsValid())
		{
			/* 
				Fill in all the Session Settings that we want to use.
				
				There are more with SessionSettings.Set(...);
				For example the Map or the GameMode/Type.
			*/
			SessionSettings = MakeShareable(new FOnlineSessionSettings());

			SessionSettings->bIsLANMatch = bIsLAN;
			SessionSettings->bUsesPresence = bIsPresence;
			SessionSettings->NumPublicConnections = MaxNumPlayers;
			SessionSettings->NumPrivateConnections = 0;
			SessionSettings->bAllowInvites = true;
			SessionSettings->bAllowJoinInProgress = true;
			SessionSettings->bShouldAdvertise = true;
			SessionSettings->bAllowJoinViaPresence = true;
			SessionSettings->bAllowJoinViaPresenceFriendsOnly = false;

			SessionSettings->Set(SETTING_MAPNAME, FString("NewMap"), EOnlineDataAdvertisementType::ViaOnlineService);

			// Set the delegate to the Handle of the SessionInterface
			OnCreateSessionCompleteDelegateHandle = Sessions->AddOnCreateSessionCompleteDelegate_Handle(OnCreateSessionCompleteDelegate);

			// Our delegate should get called when this is complete (doesn't need to be successful!)
			return Sessions->CreateSession(*UserId, SessionName, *SessionSettings);
		}
	}
	else
	{
		GEngine->AddOnScreenDebugMessage(-1, 10.f, FColor::Red, TEXT("No OnlineSubsytem found!"));
	}

	return false;
}
```

Since i commented everything and this is VERY similar to the upcoming functions, i will only explain this once:

The first thing we do is getting our OnlineSubsystem, because we need the SessionInterface from it. Once we made sure that it is valid, we get the SessionInterface and make sure this and the UsedId are valid.

Then we set a lot of different SessionSettings, like Number of Players etc. After we did this, we going to setting the delegate of the "CreateSessionsComplete" handle to the one we create and that we bound a functions to. So we make sure, that this is the one getting used and called once the "CreateSession" process is finished. We will do this for every Session operation from now on, so i won't explain this again.

Once we did this, we are going to call the "CreateSession" function of the Session Interface and we are done. Now it could take some seconds until it is finished and the Engine calls our Delegate Functions, which we will fill with logic now:

```cpp
// In our UNWGameIntance.cpp:

void UNWGameInstance::OnCreateSessionComplete(FName SessionName, bool bWasSuccessful)
{
	GEngine->AddOnScreenDebugMessage(-1, 10.f, FColor::Red, FString::Printf(TEXT("OnCreateSessionComplete %s, %d"), *SessionName.ToString(), bWasSuccessful));

	// Get the OnlineSubsystem so we can get the Session Interface
	IOnlineSubsystem* OnlineSub = IOnlineSubsystem::Get();
	if (OnlineSub)
	{
		// Get the Session Interface to call the StartSession function
		IOnlineSessionPtr Sessions = OnlineSub->GetSessionInterface();

		if (Sessions.IsValid())
		{
			// Clear the SessionComplete delegate handle, since we finished this call
			Sessions->ClearOnCreateSessionCompleteDelegate_Handle(OnCreateSessionCompleteDelegateHandle);
			if (bWasSuccessful)
			{
				// Set the StartSession delegate handle
				OnStartSessionCompleteDelegateHandle = Sessions->AddOnStartSessionCompleteDelegate_Handle(OnStartSessionCompleteDelegate);

				// Our StartSessionComplete delegate should get called after this
				Sessions->StartSession(SessionName);
			}
		}
		
	}
}
```

Here again, we will get the OnlineSubsystem and the SessionInterface. This will, again, repeat a lot of times now. Once we made sure that the SessionInterface is valid, we clear the Delegate from the handle, because the call is finished and we want to bind it next time we call "CreateSession". That's why we need to clear it.

After that, we can check if the process was "Successful". If yes, we set the Delegate of the "StartSessionComplete" handle and call the "StartSession" function with the "SessionName" we got. This is already the new Session we created!

This will also take an amount of time but once it is finished, the Engine calls the second Delegate function we created:

```cpp
// In our UNWGameIntance.cpp:

void UNWGameInstance::OnStartOnlineGameComplete(FName SessionName, bool bWasSuccessful)
{
	GEngine->AddOnScreenDebugMessage(-1, 10.f, FColor::Red, FString::Printf(TEXT("OnStartSessionComplete %s, %d"), *SessionName.ToString(), bWasSuccessful));

	// Get the Online Subsystem so we can get the Session Interface
	IOnlineSubsystem* OnlineSub = IOnlineSubsystem::Get();
	if (OnlineSub)
	{
		// Get the Session Interface to clear the Delegate
		IOnlineSessionPtr Sessions = OnlineSub->GetSessionInterface();
		if (Sessions.IsValid())
		{
			// Clear the delegate, since we are done with this call
			Sessions->ClearOnStartSessionCompleteDelegate_Handle(OnStartSessionCompleteDelegateHandle);
		}
	}

	// If the start was successful, we can open a NewMap if we want. Make sure to use "listen" as a parameter!
	if (bWasSuccessful)
	{
		UGameplayStatics::OpenLevel(GetWorld(), "NewMap", true, "listen");
	}
}
```

Similar to the first one, we get, check and clear things. Then, if everything is done and the process was again successful, we open a new Level with "listen" as a parameter. This is important!

And that's it. Now we created a Session and started it, so we are ready to get Clients on our Server/Session. But for that we need them to find our Session. So next up is "Finding Sessions".

### Searching and Finding a Session

So, once we are sure that somewhere we have a Session we can find, we can proceed with the following code.

**Searching and Finding a Session | Header File**

Function to setup our search and start the searching:

```cpp
// In our UNWGameInstance.h:

/**
*	Find an online session
*
*	@param UserId user that initiated the request
*	@param bIsLAN are we searching LAN matches
*	@param bIsPresence are we searching presence sessions
*/
void FindSessions(TSharedPtr<const FUniqueNetId> UserId, bool bIsLAN, bool bIsPresence);
```

A delegate and a handle for it:

```cpp
// In our UNWGameInstance.h:

/** Delegate for searching for sessions */
FOnFindSessionsCompleteDelegate OnFindSessionsCompleteDelegate;

/** Handle to registered delegate for searching a session */
FDelegateHandle OnFindSessionsCompleteDelegateHandle;
```

A variable for our SearchSettings which will also contain our SearchResults, once this search is complete and successful:

```cpp
// In our UNWGameInstance.h:

TSharedPtr<class FOnlineSessionSearch> SessionSearch;
```

And finally the function we want to bind to the delegate:

```cpp
// In our UNWGameInstance.h:

/**
*	Delegate fired when a session search query has completed
*
*	@param bWasSuccessful true if the async action completed without error, false if there was an error
*/
void OnFindSessionsComplete(bool bWasSuccessful);
```

**Searching and Finding a Session | CPP File**

Now filling this with logic similar to the creation process:

```cpp
// In our UNWGameInstance.cpp:

void UNWGameInstance::FindSessions(TSharedPtr<const FUniqueNetId> UserId, bool bIsLAN, bool bIsPresence)
{
	// Get the OnlineSubsystem we want to work with
	IOnlineSubsystem* OnlineSub = IOnlineSubsystem::Get();

	if (OnlineSub)
	{
		// Get the SessionInterface from our OnlineSubsystem
		IOnlineSessionPtr Sessions = OnlineSub->GetSessionInterface();

		if (Sessions.IsValid() && UserId.IsValid())
		{
			/*
				Fill in all the SearchSettings, like if we are searching for a LAN game and how many results we want to have!
			*/
			SessionSearch = MakeShareable(new FOnlineSessionSearch());

			SessionSearch->bIsLanQuery = bIsLAN;
			SessionSearch->MaxSearchResults = 20;
			SessionSearch->PingBucketSize = 50;
			
			// We only want to set this Query Setting if "bIsPresence" is true
			if (bIsPresence)
			{
				SessionSearch->QuerySettings.Set(SEARCH_PRESENCE, bIsPresence, EOnlineComparisonOp::Equals);
			}

			TSharedRef<FOnlineSessionSearch> SearchSettingsRef = SessionSearch.ToSharedRef();

			// Set the Delegate to the Delegate Handle of the FindSession function
			OnFindSessionsCompleteDelegateHandle = Sessions->AddOnFindSessionsCompleteDelegate_Handle(OnFindSessionsCompleteDelegate);
			
			// Finally call the SessionInterface function. The Delegate gets called once this is finished
			Sessions->FindSessions(*UserId, SearchSettingsRef);
		}
	}
	else
	{
		// If something goes wrong, just call the Delegate Function directly with "false".
		OnFindSessionsComplete(false);
	}
}
```

Getting OnlineSubsystem etc and filling the SearchSettings variable. Then setting the Delegate to the handle and tell the SessionInterface to "FindSessions". That's all (:

Once this is finished, the Delegate functions is called. We still need to connect these in the Constructor:

```cpp
// In our UNWGameInstance.cpp:

/** Bind function for FINDING a Session */
OnFindSessionsCompleteDelegate = FOnFindSessionsCompleteDelegate::CreateUObject(this, &UNWGameInstance::OnFindSessionsComplete);
```

And the function logic:

```cpp
// In our UNWGameInstance.cpp:

void UNWGameInstance::OnFindSessionsComplete(bool bWasSuccessful)
{
	GEngine->AddOnScreenDebugMessage(-1, 10.f, FColor::Red, FString::Printf(TEXT("OFindSessionsComplete bSuccess: %d"), bWasSuccessful));

	// Get OnlineSubsystem we want to work with
	IOnlineSubsystem* const OnlineSub = IOnlineSubsystem::Get();
	if (OnlineSub)
	{
		// Get SessionInterface of the OnlineSubsystem
		IOnlineSessionPtr Sessions = OnlineSub->GetSessionInterface();
		if (Sessions.IsValid())
		{
			// Clear the Delegate handle, since we finished this call
			Sessions->ClearOnFindSessionsCompleteDelegate_Handle(OnFindSessionsCompleteDelegateHandle);

			// Just debugging the Number of Search results. Can be displayed in UMG or something later on
			GEngine->AddOnScreenDebugMessage(-1, 10.f, FColor::Red, FString::Printf(TEXT("Num Search Results: %d"), SessionSearch->SearchResults.Num()));
		
			// If we have found at least 1 session, we just going to debug them. You could add them to a list of UMG Widgets, like it is done in the BP version!
			if (SessionSearch->SearchResults.Num() > 0)
			{
				// "SessionSearch->SearchResults" is an Array that contains all the information. You can access the Session in this and get a lot of information.
				// This can be customized later on with your own classes to add more information that can be set and displayed
				for (int32 SearchIdx = 0; SearchIdx < SessionSearch->SearchResults.Num(); SearchIdx++)
				{
					// OwningUserName is just the SessionName for now. I guess you can create your own Host Settings class and GameSession Class and add a proper GameServer Name here.
					// This is something you can't do in Blueprint for example!
					GEngine->AddOnScreenDebugMessage(-1, 10.f, FColor::Red, FString::Printf(TEXT("Session Number: %d | Sessionname: %s "), SearchIdx+1, *(SessionSearch->SearchResults[SearchIdx].Session.OwningUserName)));
				}
			}
		}
	}
}
```

After getting the OnlineSubsystem and the SessionInterface, we clear the DelegateHandle again and now we can work with the SearchResults. They are stored in the "SessionSearch" variable we created. "SessionSearch->SearchResults" is an array with all found Sessions. You can get several information from this and later on maybe create your own child class of this to add more information! I'm just printing them to the Screen.

That's all for finding Sessions. Now we can go on and try to join one.

### Joining a Session

There are different ways you can Join a session, but we will just use a Session result which we can get from the SearchResult array and joined it with help of the SessionInterface. As easy as possible.

**Joining a Session | Header file**

So the function we are going to use:

```cpp
// In our UNWGameInstance.h:

/**
*	Joins a session via a search result
*
*	@param SessionName name of session
*	@param SearchResult Session to join
*
*	@return bool true if successful, false otherwise
*/
bool JoinSession(TSharedPtr<const FUniqueNetId> UserId, FName SessionName, const FOnlineSessionSearchResult& SearchResult);
```

The delegates and the function that we bind to it:

```cpp
// In our UNWGameInstance.h:

/** Delegate for joining a session */
FOnJoinSessionCompleteDelegate OnJoinSessionCompleteDelegate;

/** Handle to registered delegate for joining a session */
FDelegateHandle OnJoinSessionCompleteDelegateHandle;
```

```cpp
// In our UNWGameInstance.h:

/**
*	Delegate fired when a session join request has completed
*
*	@param SessionName the name of the session this callback is for
*	@param bWasSuccessful true if the async action completed without error, false if there was an error
*/
void OnJoinSessionComplete(FName SessionName, EOnJoinSessionCompleteResult::Type Result);
```

Nothing fancy as Settings here. Just the functions and the delegates.

**Joining a Session | CPP file**

```cpp
// In our UNWGameInstance.cpp:

bool UNWGameInstance::JoinSession(TSharedPtr<const FUniqueNetId> UserId, FName SessionName, const FOnlineSessionSearchResult& SearchResult)
{
	// Return bool
	bool bSuccessful = false;

	// Get OnlineSubsystem we want to work with
	IOnlineSubsystem* OnlineSub = IOnlineSubsystem::Get();

	if (OnlineSub)
	{
		// Get SessionInterface from the OnlineSubsystem
		IOnlineSessionPtr Sessions = OnlineSub->GetSessionInterface();

		if (Sessions.IsValid() && UserId.IsValid())
		{
			// Set the Handle again
			OnJoinSessionCompleteDelegateHandle = Sessions->AddOnJoinSessionCompleteDelegate_Handle(OnJoinSessionCompleteDelegate);
			
			// Call the "JoinSession" Function with the passed "SearchResult". The "SessionSearch->SearchResults" can be used to get such a
			// "FOnlineSessionSearchResult" and pass it. Pretty straight forward!
			bSuccessful = Sessions->JoinSession(*UserId, SessionName, SearchResult);
		}
	}
		
	return bSuccessful;
}
```

We are doing nothing new here. Since we have no settings, we are not filling any. We are just taking the SearchResult that was passed and call "JoinSession" once we set the delegate to the handle.

And once this is finished, our function gets called again. Again, don't forget to bind it in the constructor:

```cpp
// In our UNWGameInstance.cpp:

/** Bind function for JOINING a Session */
OnJoinSessionCompleteDelegate = FOnJoinSessionCompleteDelegate::CreateUObject(this, &UNWGameInstance::OnJoinSessionComplete);
```

```cpp
// In our UNWGameInstance.cpp:

void UNWGameInstance::OnJoinSessionComplete(FName SessionName, EOnJoinSessionCompleteResult::Type Result)
{
	GEngine->AddOnScreenDebugMessage(-1, 10.f, FColor::Red, FString::Printf(TEXT("OnJoinSessionComplete %s, %d"), *SessionName.ToString(), static_cast<int32>(Result)));

	// Get the OnlineSubsystem we want to work with
	IOnlineSubsystem* OnlineSub = IOnlineSubsystem::Get();
	if (OnlineSub)
	{
		// Get SessionInterface from the OnlineSubsystem
		IOnlineSessionPtr Sessions = OnlineSub->GetSessionInterface();

		if (Sessions.IsValid())
		{
			// Clear the Delegate again
			Sessions->ClearOnJoinSessionCompleteDelegate_Handle(OnJoinSessionCompleteDelegateHandle);

			// Get the first local PlayerController, so we can call "ClientTravel" to get to the Server Map
			// This is something the Blueprint Node "Join Session" does automatically!
			APlayerController * const PlayerController = GetFirstLocalPlayerController();

			// We need a FString to use ClientTravel and we can let the SessionInterface contruct such a
			// String for us by giving him the SessionName and an empty String. We want to do this, because
			// Every OnlineSubsystem uses different TravelURLs
			FString TravelURL;

			if (PlayerController && Sessions->GetResolvedConnectString(SessionName, TravelURL))
			{
				// Finally call the ClienTravel. If you want, you could print the TravelURL to see
				// how it really looks like
				PlayerController->ClientTravel(TravelURL, ETravelType::TRAVEL_Absolute);
			}
		}
	}
}
```

Here we are doing something new. After getting the OnlineSubsystem and the SessionInterface, we clear the handle. Then we get the PlayerController of the joining Player. Since we are still on this Player, we can just get the FirstLocal one.

The we create an FString that will hold the TravelURL, which we need for a ClientTravel to the Map of the Server. How do we get the TravelURL? Easy: We tell the SessionInterface to create us one. Just pass the SessionName (which at this point is already the one of the Session we joined!) and the FString. Then we can call the ClientTravel function of the PlayerController and we are on the ServerMap, ready to play!

But now we need to also be able to destroy a Session. This is important, because Sessions take Slots on Servers and prevent us from creating new ones or join others as long as they exist.

### Destroying a Session

Destroying a Session doesn't need an extra function from us, since we don't need settings or something like that. So we only need the delegate, handle and delegate function:

**Destroying a Session | Header file**

```cpp
// In our UNWGameInstance.h:

/** Delegate for destroying a session */
FOnDestroySessionCompleteDelegate OnDestroySessionCompleteDelegate;

/** Handle to registered delegate for destroying a session */
FDelegateHandle OnDestroySessionCompleteDelegateHandle;
```

```cpp
// In our UNWGameInstance.h:

/**
*	Delegate fired when a destroying an online session has completed
*
*	@param SessionName the name of the session this callback is for
*	@param bWasSuccessful true if the async action completed without error, false if there was an error
*/
virtual void OnDestroySessionComplete(FName SessionName, bool bWasSuccessful);
```

**Destroying a Session | CPP file**

Binding the function in the Constructor!

```cpp
// In our UNWGameInstance.cpp:

/** Bind function for DESTROYING a Session */
OnDestroySessionCompleteDelegate = FOnDestroySessionCompleteDelegate::CreateUObject(this, &UNWGameInstance::OnDestroySessionComplete);
```

And filling the function with logic:

```cpp
// In our UNWGameInstance.cpp:

void UNWGameInstance::OnDestroySessionComplete(FName SessionName, bool bWasSuccessful)
{
	GEngine->AddOnScreenDebugMessage(-1, 10.f, FColor::Red, FString::Printf(TEXT("OnDestroySessionComplete %s, %d"), *SessionName.ToString(), bWasSuccessful));

	// Get the OnlineSubsystem we want to work with
	IOnlineSubsystem* OnlineSub = IOnlineSubsystem::Get();
	if (OnlineSub)
	{
		// Get the SessionInterface from the OnlineSubsystem
		IOnlineSessionPtr Sessions = OnlineSub->GetSessionInterface();

		if (Sessions.IsValid())
		{
			// Clear the Delegate
			Sessions->ClearOnDestroySessionCompleteDelegate_Handle(OnDestroySessionCompleteDelegateHandle);

			// If it was successful, we just load another level (could be a MainMenu!)
			if (bWasSuccessful)
			{
				UGameplayStatics::OpenLevel(GetWorld(), "ThirdPersonExampleMap", true);
			}
		}
	}
}
```

Doing the same with the OnlineSubsystem and the SessionInterface again and once the destruction was successful, we Open the start level again, which could be the MainMenu for example.

And that's it, this is all you need for a basic setup. You can now create Widgets or so that can use these functions, **BUT** you can't make these functions BlueprintCallable. You need a second function for each process that is BlueprintCallable.

## BlueprintCallable Functions to test this Setup

### Creating a Session

```cpp
// In our UNWGameInstance.h:

UFUNCTION(BlueprintCallable, Category = "Network|Test")
void StartOnlineGame();
```

```cpp
// In our UNWGameInstance.cpp:

void UNWGameInstance::StartOnlineGame()
{
	// Creating a local player where we can get the UserID from
	ULocalPlayer* const Player = GetFirstGamePlayer();
	
	// Call our custom HostSession function. GameSessionName is a GameInstance variable
	HostSession(Player->GetPreferredUniqueNetId(), GameSessionName, true, true, 4);
}
```

### Searching and Finding a Session

```cpp
// In our UNWGameInstance.h:

UFUNCTION(BlueprintCallable, Category = "Network|Test")
void FindOnlineGames();
```

```cpp
// In our UNWGameInstance.cpp:

void UNWGameInstance::FindOnlineGames()
{
	ULocalPlayer* const Player = GetFirstGamePlayer();

	FindSessions(Player->GetPreferredUniqueNetId(), true, true);
}
```

### Joining a Session

```cpp
// In our UNWGameInstance.h:

UFUNCTION(BlueprintCallable, Category = "Network|Test")
void JoinOnlineGame();
```

```cpp
// In our UNWGameInstance.cpp:

void UNWGameInstance::JoinOnlineGame()
{
	ULocalPlayer* const Player = GetFirstGamePlayer();

	// Just a SearchResult where we can save the one we want to use, for the case we find more than one!
	FOnlineSessionSearchResult SearchResult;

	// If the Array is not empty, we can go through it
	if (SessionSearch->SearchResults.Num() > 0)
	{
		for (int32 i = 0; i < SessionSearch->SearchResults.Num(); i++)
		{
			// To avoid something crazy, we filter sessions from ourself
			if (SessionSearch->SearchResults[i].Session.OwningUserId != Player->GetPreferredUniqueNetId())
			{
				SearchResult = SessionSearch->SearchResults[i];

				// Once we found sounce a Session that is not ours, just join it. Instead of using a for loop, you could
				// use a widget where you click on and have a reference for the GameSession it represents which you can use
				// here
				JoinSession(Player->GetPreferredUniqueNetId(), GameSessionName, SearchResult);
				break;
			}
		}
	}	
}
```

### Destroying a Session

```cpp
// In our UNWGameInstance.h:

UFUNCTION(BlueprintCallable, Category = "Network|Test")
		void DestroySessionAndLeaveGame();
```

```cpp
// In our UNWGameInstance.cpp:

void UNWGameInstance::DestroySessionAndLeaveGame()
{
	IOnlineSubsystem* OnlineSub = IOnlineSubsystem::Get();
	if (OnlineSub)
	{
		IOnlineSessionPtr Sessions = OnlineSub->GetSessionInterface();

		if (Sessions.IsValid())
		{
			Sessions->AddOnDestroySessionCompleteDelegate_Handle(OnDestroySessionCompleteDelegate);

			Sessions->DestroySession(GameSessionName);
		}
	}
}
```


# Spawn Different Pawns For Players in Multiplayer

This wiki article was written by TheJamsh.

### Overview

In this tutorial, I'll show you how I use C++ to allow a player to spawn into a Multiplayer game with a Pawn of their choice. By default, Unreal Engine allows you to choose a Pawn class that every player will use. We will change this functionality so that the Clients (and Server) can choose their Pawn way before they are spawned into the world.

### Step 1: Custom Game Mode

To start with, we need to override the 'GetDefaultPawnClassForController' function in AGameMode. Normally this function simply returns the GameModes 'DefaultPawnClass', but we want to change this so that it can hook into our custom Player Controller, and read the value from there.

**This is a much more flexible approach than creating lots of Pawn Variables in the GameMode, since we can specify any pawn class we want from our PlayerController this way!**

**MyGameMode.h**

```cpp
UCLASS()
class MYGAME_API AMyGameMode : public AGameMode
{
	GENERATED_UCLASS_BODY()
 
	/* Override To Read In Pawn From Custom Controller */
	UClass* GetDefaultPawnClassForController(AController* InController) override;
};
```

**MyGameMode.cpp**

```cpp
AMyGameMode::AMyGameMode(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer)
{
	/* Use our custom Player-Controller Class */
	PlayerControllerClass = AMyPlayerController::StaticClass();
}
 
UClass* AMyGameMode::GetDefaultPawnClassForController(AController* InController)
{
	/* Override Functionality to get Pawn from PlayerController */
	AMyPlayerController* MyController = Cast<AMyPlayerController>(InController);
	if (MyController)
	{
		return MyController->GetPlayerPawnClass();
	}
 
	/* If we don't get the right Controller, use the Default Pawn */
	return DefaultPawnClass;
}
```

Intellisense/Visual Assist will warn you that 'GetPlayerPawnClass()' doesnt' exist yet. Fear not, we'll create that in the next section!

### Step 2: Custom Player Controller

We must now invoke some custom functionality in our PlayerController, in order to tell the Gamemode which Pawn to use. On this rare occasion, we actually want the Client to have authority over the Server to ensure the Client chooses the Pawn locally, and tell the server to do the rest.

My method sets a Replicated Variable on the Server, the value of which is determined on the Client beforehand. This way, we take advantage of UE4s authoritative server system, keeping the two players in-sync and ensuring that no client-side cheating can ever occur. The server still handles the spawning of the Pawn, and the developer can choose to further validate the Clients choice if they want to.

**NOTE:** The method posted below determines which Pawn to use based on an external .txt file. This is purely because it suited our implementation, but I do NOT recommend following this method for almost any other game, since the file can be easily modified by an end user. It would be much safer and more flexible, to use a SaveGame class generated inside the game itself, and have the server verify that the Pawn is a valid option server-side.

Saving the correct Pawn to use as a SaveGame is outside the scope of this tutorial, but you can study ShooterGame's **ShooterPersistentUser** class to learn more about how to use them. Simply replace the body of 'DeterminePawnClass' with code that loads the Pawn class from your custom SaveGame.

**MyPlayerController.h**

```cpp
UCLASS()
class MYGAME_API AMyPlayerController : public APlayerController
{
	GENERATED_BODY()
 
public:
	/* Constructor */
	AMyPlayerController(const FObjectInitializer& ObjectInitializer);
 
	FORCEINLINE UClass* GetPlayerPawnClass() { return MyPawnClass; }
 
protected:
	/* Return The Correct Pawn Class Client-Side */
	UFUNCTION(Reliable, Client)
	void DeterminePawnClass();
	virtual void DeterminePawnClass_Implementation();
 
	/* Use BeginPlay to start the functionality */
	virtual void BeginPlay() override;
 
	/* Set Pawn Class On Server For This Controller */
	UFUNCTION(Reliable, Server, WithValidation)
	virtual void ServerSetPawn(TSubclassOf<APawn> InPawnClass);
	virtual void ServerSetPawn_Implementation(TSubclassOf<APawn> InPawnClass);
	virtual bool ServerSetPawn_Validate(TSubclassOf<APawn> InPawnClass);
 
	/* Actual Pawn class we want to use */
	UPROPERTY(Replicated)
	TSubclassOf<APawn> MyPawnClass;
 
	/* First Pawn Type To Use */
	UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "My Controller")
	TSubclassOf<AGESGame_ServerPawn> PawnToUseA;
 
	/* Second Pawn Type To Use */
	UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "My Controller")
	TSubclassOf<AGESGame_Pawn> PawnToUseB;
};
```

**MyPlayerController.cpp**

```cpp
AMyPlayerController::AMyPlayerController(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer)
{
	/* Initialize The Values */
	PawnToUseA= NULL;
	PawnToUseB= NULL;
 
	/* Make sure the PawnClass is Replicated */
	bReplicates = true;
}
 
void AMyPlayerController::BeginPlay()
{
	Super::BeginPlay();
 
	DeterminePawnClass();
}
 
// Pawn Class
void AMyPlayerController::DeterminePawnClass_Implementation()
{
	if (IsLocalController()) //Only Do This Locally (NOT Client-Only, since Server wants this too!)
	{
		/* Load Text File Into String Array */
		TArray<FString> TextStrings;
		const FString FilePath = FPaths::GameDir() + "Textfiles/PlayerSettings.txt";
 
	        /* Use PawnA if the Text File tells us to */
		if (TextStrings[0]== "PawnA")
		{
			ServerSetPawn(PawnToUseA);
			return;
		}
 
	        /* Otherwise, Use PawnB :) */
		ServerSetPawn(PawnToUseB);
		return;
	}
}
 
bool AMyPlayerController::ServerSetPawn_Validate(TSubclassOf<APawn> InPawnClass)
{
	return true;
}
 
void AMyPlayerController::ServerSetPawn_Implementation(TSubclassOf<APawn> InPawnClass)
{
	MyPawnClass = InPawnClass;
 
	/* Just in case we didn't get the PawnClass on the Server in time... */
	GetWorld()->GetAuthGameMode()->RestartPlayer(this);
}
 
// Replication
void AMyPlayerController::GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const
{
	DOREPLIFETIME(AMyPlayerController, MyPawnClass);
}
```

### Client/Server Functions

The **most important functionality** in the Player Controller is NOT necessarily how you determine which pawn to use, but is actually the use of Client/Server functions and the Replicated 'MyPawnClass' variable. Without this, the Server will never know which Pawn the Client wants to spawn.

Also note the use of 'IsLocalPlayerController()' during the 'DeterminePawnClass' function. This is a check to ensure that the Server doesn't try to load it's own TextFile for the player, and ensures that the Client tells the Server which Pawn it wants to use, not the other way around. Without it, all of the players will actually end up using the Servers' chosen Pawn, regardless of what they really want to do! Don't replace this with an Authority check, since the Server could also be a player!

### Text File Implementation

If you want to use this functionality exactly as it's posted above, you need to create a folder in your projects' Root Directory called 'TextFiles', and in there create a new .txt file called 'PlayerSettings.txt'

The Player Controller will search for the file on BeginPlay and attempt to load the text inside it into an array of strings. Each line in the text file forms another element in the array. If the first line in the text file is 'PawnA', the controller will tell the GameMode to use 'PawnToUseA' for this player. If any other value is entered or no value is found, it will instead use 'PawnToUseB'.

### Assertion

I **Strongly Recommend** you add additional checks and/or asserts to the above code. The final code that I actually use does have this in place, but I used an alternative Assert Library that I do not have permission to share, and so cut them out. Remember, you should always check if something valid and never allow your code to de-reference a NULL pointer!

If a .txt file isn't found for the example posted above, it will crash the engine. If you want to build a packaged version of your game, you **must** copy the TextFiles folder into the games' folder when packaging has finished!

### Final Word

I do NOT encourage the use of TextFiles to determine which pawn to use for a real project. The code above is only meant to show the order of operations, and the use of Client/Server functionality to ensure reliability. It was suitable only for a very unique implementation. I highly recommend modifying the 'DeterminePawnClass' function to return a Pawn class from a SaveGame, or similar. This method is much more secure and less prone to errors.

In due time, I will update this tutorial to do exactly that, as I believe it is much more suited to most projects. More advanced C++ users will be able to integrate this on their own from this point on however, so enjoy!

Hope this helps!


# Spawn Different Pawns For Every Player

Not every player is likely going to use DefaultPawnClass as their Pawn and my quick search through the UE4 community didn't result in any information. The Shooter example touches on this but only handles the difference between AI and Player, and not what to do if you have multiple Pawns that a player can select.

The first question I had when starting into this was where to store the information that tells the server what player is using what Pawn. I think the reason I struggled with this for so long was simply because the class that really holds information about a player is named APlayerController and that led me to believe that I really should only be using it for input from the player. So very very wrong. The APlayerController class is perfectly suited for this usage.

So the first thing I did was create a new struct to hold information about the players chosen Pawn. In the example below I only have one int32 as a property, but in our actual code we're storing much more about the Pawn that is required at spawn such as items the player may have equipped. For the purposes of this tutorial though the below is enough.

```cpp
struct PlayerPawnData
{
	int32 Type;
};
```

Then inside your custom [APlayerController](https://web.archive.org/web/20161008074957/https://docs.unrealengine.com/latest/INT/API/Runtime/Engine/GameFramework/APlayerController/index.html) declaration you'd want to define a public property that uses this struct as it's type.

```cpp
PlayerPawnData CurrentPawnData;
```

With this data now available in your APlayerController declaration lets move to the custom AGameMode you've defined for your UE4 game.

There are a few functions inside AGameMode that are important to respawning a player. The first is RestartPlayer and the name of this function should make it's use pretty self-explanatory. This function is called when a player spawns, whether it's when they've first joined or just died. The functions that are called inside RestartPlayer is what we're going to focus on, primarily GetDefaultPawnClassForController.

The basic functionality of GetDefaultPawnClassForController simply returns the member variable DefaultPawnClass but for this game that isn't going to work since each player could have a different Pawn class. That means we're going to have to override this function entirely. Lets start with the declaration inside your custom AGameMode class.

```cpp
virtual UClass* GetDefaultPawnClassForController(AController* InController) OVERRIDE;
```

We'll also need some sort of storage so we can reference the Pawn class using the type provided inside the PlayerPawnData variable on the APlayerController.

```cpp
TMapBase<int32, UClass*, false> PawnTypes;
```

So we've marked GetDefaultPawnClassForController as an override and we have a place to store our pawn types now lets create the functionality. Same as the examples above I've simplified the code for this tutorial. We've got a little more going on inside our GetDefaultPawnClassForController.

```cpp
UClass* AMyGameMode::GetDefaultPawnClassForController(AController* InController)
{
	AMyPlayerController* PlayerController = Cast<AMyPlayerController>(InController);

	UClass* PawnClass = PawnTypes.Find(PlayerController->CurrentPawnData.Type);

	return PawnClass;
}
```

So what's happening above? We're casting the incoming AController into our custom APlayerController and then referencing the CurrentPawnData's property Type to find the correct Pawn to spawn. With just this overridden the UE4 base AGameMode class will start spawning the correct Pawn when the player joins or dies.

I'm sure there's a different way to go about doing this but this felt right to me. Storing the actual UClass would be an option but because in our specific use case we're storing more than just the UClass to spawn but also base stats pertaining to that Pawn type I went with just storing the type.

Reposted from [http://www.osnapgames.com/2014/06/17/spawn-different-pawns-depending-on-player-selection/](https://web.archive.org/web/20161008074957/http://www.osnapgames.com/2014/06/17/spawn-different-pawns-depending-on-player-selection/)


# Gameplay Abilities and You

This wiki article was written by KJZ in a forum post.

## Introduction

*This is here for archival reasons, however, there are more updated resources such as the* [*GASDocumentation*](https://github.com/tranek/GASDocumentation) *and* [*GASShooter*](https://github.com/tranek/GASShooter) *repos*

So, what's a GameplayAbility?

Basically, they're like the abilities you have in Dota or equivalent games. You can cast a fireball, and this fireball hits a player, explodes (doing a set amount of damage), and sets everyone in the radius of the explosion on fire (doing damage over time). Meanwhile, the player who cast the fireball loses some mana and is put on cooldown.

You could use Epic's GameplayAbility plugin to do all of those things. The module is hard to wrap your head around, but once you learn how powerful they can be and how to properly make use of them, they can make your life much, much easier.

But why use this over rolling your own system?

GameplayAbilities can come in handy if your game is in need of a powerful skill, buff and attribute system that is both easy to extend and crazy-efficient to replicate. This can do wonders for people working on a multiplayer RPG with a lot of skills/classes or perhaps even a MOBA, but you can use this system for pretty much any game you want. The main problem is that it isn't the easiest to comprehend, quite big and may get a little in your way the further you stray too far away from this multiplayer RPG ideal, so not every game will get the same mileage out of it.

Well, that sounds like a dream, but where do I get it?

Well, first of all, GameplayAbilities is a code module that used to be integrated into UE4's source, but since this current version (4.15, that is, people from the future) has been moved into a separate plugin that is delivered alongside the Unreal Engine, so that it may not take away space in your games if they do not make use of the system. This system does not actually originate as a built-in engine feature, but has, in fact, been kindly left in there from the developers of Paragon and Fortnite for third parties to enjoy. Unfortunately, due to these unique circumstances, the module as a whole is quite messy, poorly (read: barely at all, your best bet are code comments and even those are only there like half the time) documented, and rarely updated and cleaned up.

It is also not 100% exposed to blueprints, partially, but not entirely, due to a lot of the system abusing a lot of engine trickery and magic to work as well as they do, so if you never worked with C++ in the context of UE4, you may want to turn back and maybe do a little tutorial on that now, because this tutorial will make for a poor first learning experience.

In other words, it is a total flippin' pain in the buttocks to wrap your head around, but that's where this guide comes in to help ya. [Epic Developer Dave Ratti has an example GitHub project](https://github.com/daveratti/GameplayAbilitiesSample) which goes through some basic examples to get you started, but ignores the fine lines and goes for broad strokes. The project itself has been pretty hidden, however, and (at the time) doesn't really show up on Google or any real search about the GameplayAbilities plugin, so it hasn't been as helpful as a full-fledged guide. Moreover, now that GameplayTags are properly integrated into the editor by default (a system GameplayAbilities itself uses at every corner of the way, acting as GameplayAbilities' backbone), setup has never been any easier!

With all that said, let's get started, finally.

## Getting Started

### Setting up the project

So, first of all, let us create an all-new C++ third person project, not just because I want you to properly understand the specifics of enabling the system for your own use, but also because I want to start on a clean slate so that you may not be confused by assets which you do not have on hand.

![Project Creation](https://github.com/NickGlenn/Unreal-Engine-4-Community-Guide/tree/58f38c224a525dc8480d25ca361411d9d3e3ff4c/.gitbook/assets/gameplayabilities-project-creation.png)

This should be a fairly straightforward and obvious step to anyone that has ever created a UE4 C++ project before. I'm calling it GameplayAbilitiesTut, but you may call it as you'd like, really, as long as you pay attention and replace my project's name with yours while coding and understanding. Alright, we're here. Good old third person template, such a familiar environment, and so useful for tutorials! We want to open the plugin menu, accessed through the Settings tab.

![Plugins](https://github.com/NickGlenn/Unreal-Engine-4-Community-Guide/tree/58f38c224a525dc8480d25ca361411d9d3e3ff4c/.gitbook/assets/enabling-plugins.png)

We find GameplayAbilities in the Gameplay category. Enable it. Do not be scared off by the big scary "\[UNSUPPORTED]" in the description or the prompt that asks you if you're sure. You know darn well you're sure! You must now restart the editor to fully enable the plugin. It contains a few menus and a new blueprint type to select from the new asset-menu, but it won't load those until the next restart.

After you restart, you may or may not notice a few new things: A new blueprint type called "Gameplay Ability Blueprint" when you press right-click in the content browser to create a new blueprint and a new window in the window menu called "GameplayCue Editor".

![Cue Editor](https://github.com/NickGlenn/Unreal-Engine-4-Community-Guide/tree/58f38c224a525dc8480d25ca361411d9d3e3ff4c/.gitbook/assets/gameplaycue-editor.png)

![Ability Blueprint](https://github.com/NickGlenn/Unreal-Engine-4-Community-Guide/tree/58f38c224a525dc8480d25ca361411d9d3e3ff4c/.gitbook/assets/gameplayability-blueprint.png)

We don't go into specifics with these just yet, but we do want to create a Gameplay Ability Blueprint, mostly because it's pretty much just a generic blueprint for abilities, and we will need one to test our AbilitySystemComponent later.

Select "GameplayAbility" as your blueprint's parent, name it Use\_Spell\_1, open the blueprint and just link a Print String node to the ActivateAbility event. Now you know when your AbilitySystem successfully calls your ability, because then a reassuring light-blue "Hello." will show on the screen. Self-explanatory, really.

### Setting up our Character

Alright, I hope you got your Visual Studio ready already, it's time for some nitty gritty code. We want to give our character an ability component to use.

... well, not quite, anyway. We need to tell our compiler that we want to use the GameplayAbilities module first. Go into your project's `Build.cs` file(in my case it's `GameplayAbilitiesTut.Build.cs`) and change this

```csharp
PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore", "HeadMountedDisplay" });
```

to this

```csharp
PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore", "HeadMountedDisplay", "GameplayAbilities" });
```

Basically, we add "GameplayAbilities" to the list. Don't worry about getting it wrong, your compiler will immediately start nagging if it can't find the module with the name you typed in. Adding the module name into this list assures that the module will be properly linked to our project. Without it our compiler would throw out a bunch of confusing external linker errors each time we were to include a header from this module into our project's files.

Now, open your project's C++ character. This will be GameplayAbilitiesTutCharacter for me. Go into the class header and declare a new pointer to a UAbilitySystemComponent right below your other component pointers. You should also give it a UPROPERTY macro. It's okay to copy and paste the UPROPERTY from your camera components, but you should probably change the category to something like "Abilities" for clarity reasons. It should look a little like this.

```cpp
/** Camera boom positioning the camera behind the character */
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Camera, meta = (AllowPrivateAccess = "true"))
class USpringArmComponent* CameraBoom;

/** Follow camera */ UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Camera, meta = (AllowPrivateAccess = "true"))
class UCameraComponent* FollowCamera;

/** Our ability system */ UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Abilities, meta = (AllowPrivateAccess = "true"))
class UAbilitySystemComponent* AbilitySystem;
```

What is also extremely important, so we don't get into trouble later down the line, is to make it so that our character implements the `IAbilitySystemInterface`. The guide assumes basic programming knowledge, you should know about what an interface does, so I won't get too much into detail, but it allows us to define a pseudo-parent of sorts that defines functions we have to override. This interface here gives other actors an easy way to both know we have an ability system, and a way to get it without doing something dumb and inefficient like iterating through our components for an ability system. Many features will not run properly without this interface implemented. Our code until now would run fine without it, but you will head into trouble once we're done with our initial setup and want to throw buffs and similar things on our character.

```cpp
#include "AbilitySystemInterface.h" //We add this include.

UCLASS(config=Game)
class AGameplayAbilitiesTutCharacter : public ACharacter, public IAbilitySystemInterface //We add this parent.
{
    UAbilitySystemComponent* GetAbilitySystemComponent() const override //We add this function, overriding it from IAbilitySystemInterface.
    {
        return AbilitySystem;
    };
}
```

Further, we go into our cpp file and go to the constructor of your character. For me that is `GameplayAbilitiesTutCharacter.cpp`. We need to actually create the component, and have our pointer point to it. As you will actually create an object of type `UAbilitySystemComponent` now, you must include `"AbilitySystemComponent.h"` in your cpp file. Top of the file up to constructor should look a little like this now.

```cpp
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
include "GameplayAbilitiesTut.h"
include "Kismet/HeadMountedDisplayFunctionLibrary.h"
include "GameplayAbilitiesTutCharacter.h"
include "AbilitySystemComponent.h"
////////////////////////////////////////////////////////////////////////// // AGameplayAbilitiesTutCharacter

AGameplayAbilitiesTutCharacter::AGameplayAbilitiesTutCharacter()
{ 
    // Set size for collision capsule
    GetCapsuleComponent()->InitCapsuleSize(42.f, 96.0f);
    // set our turn rates for input
    BaseTurnRate = 45.f;
    BaseLookUpRate = 45.f;

    // Don't rotate when the controller rotates. Let that just affect the camera.
    bUseControllerRotationPitch = false;
    bUseControllerRotationYaw = false;
    bUseControllerRotationRoll = false;

    // Configure character movement
    GetCharacterMovement()->bOrientRotationToMovement = true;

    // Character moves in the direction of input...
    GetCharacterMovement()->RotationRate = FRotator(0.0f, 540.0f, 0.0f);

    // ...at this rotation rate
    GetCharacterMovement()->JumpZVelocity = 600.f;
    GetCharacterMovement()->AirControl = 0.2f;

    // Create a camera boom (pulls in towards the player if there is a collision)
    CameraBoom = CreateDefaultSubobject<USpringArmComponent>(TEXT("CameraBoom"));
    CameraBoom->SetupAttachment(RootComponent);
    CameraBoom->TargetArmLength = 300.0f; // The camera follows at this distance behind the character 
    CameraBoom->bUsePawnControlRotation = true; // Rotate the arm based on the controller

    // Create a follow camera
    FollowCamera = CreateDefaultSubobject<UCameraComponent>(TEXT("FollowCamera"));
    FollowCamera->SetupAttachment(CameraBoom, USpringArmComponent::SocketName); // Attach the camera to the end of the boom and let the boom adjust to match the controller orientation
    FollowCamera->bUsePawnControlRotation = false; // Camera does not rotate relative to arm

    // Our ability system component.
    AbilitySystem = CreateDefaultSubobject<UAbilitySystemComponent>(TEXT("AbilitySystem"));

    // Note: The skeletal mesh and anim blueprint references on the Mesh component (inherited from Character)
    // are set in the derived blueprint asset named MyCharacter (to avoid direct content references in C++)
}
```

You may try to compile if you are unsure whether you did everything the right way.

Once you have compiled, you can open your character blueprint(which inherits from your C++ character) and lo and behold, right under the character's movement component you should see an `AbilitySystemComponent`.

![Ability System Component Added](https://github.com/NickGlenn/Unreal-Engine-4-Community-Guide/tree/58f38c224a525dc8480d25ca361411d9d3e3ff4c/.gitbook/assets/abilitysystemcomponent-added.png)

Alright, well... what now? The blueprint menu for the component is not helpful at all, and none of the nodes you get by dragging off AbilitySystem are particularly useful, either. There's these "Try Activate Ability" nodes, but you may find out that these things don't do anything right now. That's because the ability system doesn't have any abilities to activate yet, nor does it have any inputs assigned to them, anyway, so trying to activate an ability you do not have is, obviously, a quite useless effort. We will work on fixing both things. You must do both things in C++.

### Binding to Character Input

First of all, we will bind our ability system to our character's input, because it's the slightly more complicated issue and it's actually pretty interesting on how you do it. So first of all, go back to your character's cpp file, and go to the SetupPlayerInputComponent function. It's the one responsible for binding your character's inputs to the player controlling it, and takes a UInputComponent as parameter. This is important, we need it to bind our ability system to it. We want to call AbilitySystem->BindAbilityActivationToInputComponent within the SetupPlayerInputComponent. It takes two parameters: The UInputComponent pointer at hand and a struct called `FGameplayAbiliyInputBinds`. ***This is not a typo!*** It is not called **FGameplayAbilityInputBinds**, but **FGameplayAbiliyInputBinds!**

***Note: Latest as of 4.24 this typo has been fixed.***

The constructor for `FGameplayAbiliyInputBinds` takes at least 3 parameters: The first two are strings, and represent the input names that will be used to define "Confirm" and "Cancel"-input commands. You do not necessarily need these depending on your game, but abilities can be set up to listen to these while they're active, and targeting actors (basically, actors that return an ability viable targets/locations to aim at for an ability, if an ability requests one) will use these too, so generally it can't hurt to have these even if you will never use them. The third parameter is the name of an arbitrary UEnum of all things. This is one of the witchcraft-ier aspects of the system: The ability system component will look into the enum whose name you've given and will map its ability slots to the names of the elements contained within the enum. This probably sounds way complicated from the way I'm describing this, but it's actually quite simple. This is an input enum lifted from my own project:

```cpp
//Example for an enum the FGameplayAbiliyInputBinds may use to map input to ability slots.
//It's very important that this enum is UENUM, because the code will look for UENUM by the given name and crash if the UENUM can't be found. BlueprintType is there so we can use these in blueprints, too. Just in case. Can be neat to define ability packages.
UENUM(BlueprintType) 
enum class AbilityInput : uint8
{
    UseAbility1 UMETA(DisplayName = "Use Spell 1"), //This maps the first ability(input ID should be 0 in int) to the action mapping(which you define in the project settings) by the name of "UseAbility1". "Use Spell 1" is the blueprint name of the element.
    UseAbility2 UMETA(DisplayName = "Use Spell 2"), //Maps ability 2(input ID 1) to action mapping UseAbility2. "Use Spell 2" is mostly used for when the enum is a blueprint variable.
    UseAbility3 UMETA(DisplayName = "Use Spell 3"),
    UseAbility4 UMETA(DisplayName = "Use Spell 4"),
    WeaponAbility UMETA(DisplayName = "Use Weapon"), //This finally maps the fifth ability(here designated to be your weaponability, or auto-attack, or whatever) to action mapping "WeaponAbility".
    //You may also do something like define an enum element name that is not actually mapped to an input, for example if you have a passive ability that isn't supposed to have an input. This isn't usually necessary though as you usually grant abilities via input ID,
    //which can be negative while enums cannot. In fact, a constant called "INDEX_NONE" exists for the exact purpose of rendering an input as unavailable, and it's simply defined as -1.
    //Because abilities are granted by input ID, which is an int, you may use enum elements to describe the ID anyway however, because enums are fancily dressed up ints.
}
```

Basically, this means we need to define an enum, too. Let's just do it in our `GameplayAbilitiesTutCharacter`'s header. You may copy-paste this enum here if you wish, (and this tutorial will do just that), even if 5 slots may be a little overkill for the purpose of example. Finally, our function should look something like this:

```cpp
AbilitySystem->BindAbilityActivationToInputComponent(PlayerInputComponent, FGameplayAbiliyInputBinds("ConfirmInput", "CancelInput", "AbilityInput"));
```

Place this code at the end of your `SetupPlayerInputComponent` function, and you should be gravy. You have successfully bound your ability system's ability activation to player input!

### Giving the Character an Ability

The final step of our setup is to finally give the character an ability of choice. For simplicity's sake we will only give him one on the action mapping "UseAbility1" and just give the actor a variable that defines which ability to put there, but the same principles for granting one ability are applicable for multiple ones. We will make it blueprint-editable too so we can easily change the ability we want to test later down the line.

Our variable will be a `TSubclassOf<UGameplayAbility>`, because we get all relevant info from the class alone. In fact, GameplayAbilities can be set up to only instance per activation or not to instance at all even, so giving an instance we can freely change beforehand would be a weird idea, anyway.

```cpp
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Abilities)
TSubclassOf<class UGameplayAbility> Ability;
```

In BeginPlay, we will call AbilitySystem's `GiveAbility` function. We actually wrap this in an if-statement that first checks if we are authority. If a client tries to give himself an ability, an assert is violated and the game goes to crash and burn, taking the editor with it. You've been warned. Only give abilities on the server... or else! We'll also need to check if Ability is valid, and not NULL/nullptr.

`GiveAbility` requests an `FGameplayAbilitySpec` as parameters. An `FGameplayAbilitySpec` is the data surrounding a `GameplayAbility`, notably which level (the system has built-in support for a level variable, quite good for RPGs/MOBAs as mentioned) and which input ID it is.

`FGameplayAbilitySpec` requests a `GameplayAbility` object as parameter, but that's not a problem; we can just give the Ability class' default object as parameter. There is very little reason to use anything other than the default object of a `GameplayAbility` class as far as I've understood it from going through the source. Finally, while on the topic of BeginPlay, we should also call `AbilitySystem->InitAbilityActorInfo`. It tells the AbilitySystem what its Owner (the actor responsible for the AbilitySystem) and Avatar (the actor through which the AbilitySystem acts, uses Abilities from etc.) is. In our case our character is both. Our final BeginPlay should look something like this:

```cpp
void AGameplayAbilitiesTutCharacter::BeginPlay()
{

  Super::BeginPlay();
  if(AbilitySystem)
  {
     if (HasAuthority() && Ability)
     {
        AbilitySystem->GiveAbility(FGameplayAbilitySpec(Ability.GetDefaultObject(), 1, 0));
     }
     AbilitySystem->InitAbilityActorInfo(this, this);
  }
}
```

You also need to make sure that the AbilitySystemComponent's ActorInfo struct is being updated each time the controller changes. On the surface much of the system will work without that, but in a multiplayer enviroment especially(where pawns may be spawned before the client controller possesses them) you will experience crashes and behaviour that can be difficult to debug should you not properly set the ActorInfo up. Override your character's/pawn's OnPossessed function like so:

```cpp
void AGameplayAbilitiesTutCharacter::PossessedBy(AController * NewController)
{
   Super::PossessedBy(NewController);
   AbilitySystem->RefreshAbilityActorInfo();
}
```

Compile, add an action input mapping in your project settings called "UseAbility1" and start the game. If the game doesn't crash and the mapped input produces a plain old "Hello.", then congratulations! You have successfully set up your gameplay ability system for this character.

Note that if it crashes and spits out an error message talking about AbilityActorInfo being invalid, try adding this code just before the HasAuthority() check and seeing if it fixes the problem:

```cpp
FGameplayAbilityActorInfo* actorInfo = new FGameplayAbilityActorInfo();
actorInfo->InitFromActor(this, this, AbilitySystem); 
AbilitySystem->AbilityActorInfo = TSharedPtr<FGameplayAbilityActorInfo>(actorInfo);
```

That was the worst and dryest part, so you are allowed to be proud of yourself! We can finally move on to the actually exciting part of using the system.

## The Essentials

Alright, you should now have at least one functional GameplayAbility bound to your character, which is pretty cool. However, we haven't even gotten into what GameplayAbilities can do yet. Heck, we haven't gotten to what anything at all does yet, because setup took so long. However, GameplayAbilities are a great place to start general comprehension.

### GameplayAbilities

#### Overview

GameplayAbilities are the stupidly flexible implementation of spells, skills and such in this system. Not only do they have easy support for such things as cooldown, costs and other common RPG-ish stock spell features, but they are set up in such a way that you may call so-called Ability Tasks within them. These are specialized asynchronous tasks that you may request to run during an ability's active period, returning to the blueprint graph once the task has completed its task, or until a certain event or passage of time prompts the task to call back.

They're in a sense very much like your run-of-the-mill Blueprint Delay node, but they can do oh-so-much-more than just waiting a certain amount of time to continue. They may, for instance, wait for an input, or for a collision/overlap, or for a montage to finish playing(going to a different execution path when ending normally or when interrupted), they can even wait for client and server to sync up to a certain point. This means that an ability must not immediately be done after the initial activation frame, but may consist of one to several different time-consuming processes before finally being finished.

Wait for an animation to finish playing before firing a fireball? Easy. Charge the fireball by holding down the button mapped to the ability, releasing the button to fire the fireball? Easy. Heck, you could probably program an ability that forces you to play DDR with your fingers before shooting a fireball, with the fireball getting stronger with godlike finger dancing skills, if you really wanted to.

This comes at a small price though, because an ability activation always needs to directly or indirectly call EndAbility to announce that its Activation has ended. By default you will be unable to trigger an activation past the first one (though there is an option to be able to reset a running ability when pressing the activate-button), and it will be considered permanently active for all intents and purposes. This may mess with other abilities or aspects of the system. You must also manually call "Commit Ability" within the ability activation, which checks for and applies the likes of cost and cooldowns.

An ability is also able to control its own instancing state, and each ability may independently choose whether they do not want to be instanced (no ability tasks, no personal state and variables and some other limited functionality, but ridiculously cheap so preferable if you can get away with it), instanced on activation (personal state limited to a per-activation basis, variables and such can be replicated but it is not recommended) or instanced per ability owner (most expensive, but variables can easily be replicated, state can be carried across activations \[for example, a fireball that gets stronger with each use would be possible without permanently considering the ability active] and most functions are intact).

Finally, abilities can be useful for certain passive effects too, as abilities can listen for tags being granted upon their owners or Gameplay Events firing in the owning Ability System Component (more on that another time). Buffs that respond to certain outside influences may implement themselves by granting the affected actor with a hidden passive ability to listen for these, for example.

As such, GameplayAbilities are extremely useful, and you'd do good to learn how to best make use of them.

**Notable Variables**

* **Ability Tags:** Gameplay Tags the ability uses as flags, so to speak. Gameplay Tags are pretty much a global list of names and terms that can be used by assets as generic names and labels. In the context of GameplayAbilities these can be useful by having a GameplayAbility use an Ability Task to listen for the activation of a different ability with specified tag as ability tag.
  * Alternatively, an ability may cancel other currently active abilities that are described to have ability tag X, or it may be blocked from activating while ability with ability tag X is active. These are easy ways to set up global behaviour and interaction between different abilities. Perhaps only one transformation can be active at a time? Perhaps activating fire magic while water magic is active cancels one or both? It's up to you and what type of game you want to make. There are no strict rules.
* **Cancel Ability with Tags:** Abilities with these tags will be cancelled upon activation of this ability.
* **Block Ability with Tags:** Abilities with these tags will be blocked while this ability here is active.
* **Activation Owned Tags:** The Owner of the ability gets these tags while the ability is active. This is something different than **Ability Tags**, because the owner gets these here. GameplayEffects (buffs) may interact with them this way, and other abilities can, as already mentioned, listen for a tag to be granted to its owner to active. This has a lot of uses if you get creative with it, you could make the user of the ability immune to damage while they are casting this, etc.
* **Activation Required Tags:** The Owner has to have these tags ***BEFOREHAND*** so that it may become activatable. Great for, say, buffs that allow you access to strong abilities, or perhaps status effect-purging abilities that are only activatable as you are affected by the status effect at hand.

  Activation Blocked Tags: Same as Activation Required Tags but in reverse: the Owner of the ability must not have these tags. Excellent for crowd control effects such as silences, stuns, roots (which, in some games, disable movement-related abilities), you name 'em.
* **Source Required Tags:** The source must have these tags. What the system considers "source tags" is not immediately obvious because it isn't explained anywhere, but you can trigger abilities with payloads containing this information using a feature called GameplayEvents, which are detailed much further down below. The GameplayEvent will pass a struct which you can fill out as you please beforehand, with the InstigatorTags in that struct acting as the tags used in the Source Required and Source Blocked checks. When the payload contains all tags here specified in some capacity, the ability activation is allowed.
* **Source Blocked Tags:** See **Source Required Tags**. Same applies, but instead of checking if all described tags are present, it checks if none of the blocked tags are present in the payload. If a blocking tag is present, the activation will be stopped.
* **Target Required Tags:** See **Source Required Tags**. Same rules apply, but the tag container "TargetTags" from the GameplayEvent payload is used. It stands to reason that the InstigatorTags should be filled out with either the currently applied or at least descriptive tags of the actor owning the ability and firing it, and the TargetTags should be filled out with info relevant to who will get hit by this ability activation. As the code doesn't really enforce how you're filling out the tag containers in the GameplayEvent data however, you're free to do whatever you like, really.
* **Target Blocked Tags:** Same as **Target Required Tags** but with Blocked tags.
* **Cost GameplayEffect:** This is a GameplayEffect (in a sense a buff, or instant stat modifying action) that may contain instant, and thus permanent, stat modifiers, for example for mana and stamina and such. This checks if the attribute in question will be lowered below 0 by one such instant modifier. If so, Commit Ability will prompt the ability to end prematurely.
* **Ability Triggers:** Can be used for remote ability activation. You can choose to activate the ability in response to a tag being granted to the owner, the tag being present on the owner (ending the ability automatically when the tag ceases applying(?)), or a Gameplay Event labelled with the specified tag being handled by the ability's owning Ability System Component.
* **Cooldown GameplayEffect:** This GameplayEffect represents the ability's cooldown. When checking for cooldown, the ability will look into this gameplay effect's granted tag container (the tags it may grant to the owner while active) and will then check if the using ability system has any of these tags granted to them. If yes, the ability will be considered on cooldown.
  * This essentially means that all independent cooldowns need their own dedicated gameplay tag, but it also means that multiple abilities can easily share a cooldown, outside events may easily set a particular cooldown and one ability may also have a gameplay effect sharing cooldowns with 2 different kinds of cooldowns that do not influence each other.
  * A cooldown gameplay effect can also be set to 0/really low so that you may set the cooldown manually with the tags specified in the dedicated cooldown GameplayEffect as the ability is running, which can be useful if your ability doesn't always have a predictable and predefined cooldown in mind.

### GameplayTasks

#### Overview

Fairly self-explanatory; AbilityTasks are Blueprint nodes you can call in Ability graphs that wait for an outside stimuli before continuing. AbilityTasks inherit from so-called GameplayTasks, which generally have very similar usages that involve calling a blueprint node that may call back to the graph later, but while GameplayTasks are intended for much more general usage that covers things from giving an AI commands to follow to completion to simply acting as slightly expanded Delay node, AbilityTasks are specialized for usage within(and only within) GameplayAbilities. AbilityTasks usually possess an unlabelled top exec route that you may use to continue calling functions within the current frame and labelled exec pins that will run its attached route of functions at a later time, much like how delays work but with things other than time, usually.

They usually do what they advertise in their name/description, they support multiplayer because the server will generally always call them because the ability itself will generally always be called on the server, and will do their best predicting because the client will usually call them first unless specified otherwise by you. They do not actually have innate systems for correcting predictions on their own, but the things you do change with them usually will be replicated/will have systems to prevent desyncs themselves, so for the built-in tasks this is rarely a problem. Still, you should be wary of that when writing your own task classes.

Tasks will only run for as long as the ability is active, so the `EndAbility` node will prematurely end all pending ability tasks originating from that ability, as well. Because of this, you probably want to place things that **HAVE** to happen, no matter how the ability ended, in the EndAbility function. One example I could think off probably being purging off a buff that roots you in place as you play your casting animation.

Furthermore, because abilities have to remain active to use their tasks and abilities can really only track their state for their current activation, this also means that, for example, projectiles with elaborate effects should try to find a workaround over constantly keeping the ability active until they hit something/cease to exist, unless said projectile actively occupies the character or there is other similar reasons ability duration and projectile lifetime have to be so tightly knit together.

The rest of this section will be about creating your own custom task. You are free to skip to the usage example for Blueprints further down below for now if you have no reason to create your own task at the moment. You won't exactly have to make your own custom task often, this bit here is mostly so you don't feel too lost if you have to actually do one yourself.

Creating an AbilityTask is relatively simple, but it's not immediately obvious how you're supposed to do it. It's also not actually needed unless you have an outside system you need to incorporate into abilities somehow, and that has any meaningful callbacks to send back to these abilities. I personally have created a custom ability task for a melee attack system component that I intend to use, that first plays an attack montage and then calls back using delegates each time a new enemy has been hit by an attack's hitbox, and finally when the montage ends and the attack ceases. With these delegate callbacks it is possible to implement custom on-hit logic from the comfort inside your ability and still let the melee system do all the heavy lifting for you. Being able to have bigger procedures and actions be all handled within a compact and easy task node while you just have to implement what happens after which events is a huge boon and a big reason to use them where they make sense!

First, you must include the GameplayTask module in your build files. GameplayTasks are the overarching system AbilityTasks use to create asynchrous nodes in abilities, so trying to create new AbilityTasks without adding this module first will usually result in Linker errors:

```cpp
PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore", "HeadMountedDisplay", "GameplayAbilities", "GameplayTasks"} );
```

Now create your AbilityTask object in the UE4 C++ file explorer. I'm calling mine AbilityTask\_MyTask, but you may want to rename it depending on what you want it to do. You know the drill.

Once you have created a new, empty class that inherits from AbilityTask, you should first of all define a static function in there that will help creating the AbilityTask within an ability BP. Technically you can put this static function anywhere really, but having it in your class is easy and makes it easy to find if you need to change it, too.

They're all set up about the same way, just a static function taking an OwningAbility, a task name and some optional extra variables(depending on usage) as parameters, returning a task of the type you want to return, with the UFUNCTION properties further easing and streamlining it for BP use:

```cpp
/* This UFUNCTION macro describes, in that order:
The function can be called in BP, the category in which 
the function will de displayed in the BP-function-
dropdown is "Ability", subcategory "Tasks", the function 
name in BP is displayed as "ExecuteMyTask",
the pin for the parameter "OwningAbility" is hidden in BP 
and the parameter "OwningAbility" will default to 
the object the calling graph belongs to, if applicable. 
Finally, BlueprintInternalUseOnly = "TRUE" prevents
a regular function node for this UFUNCTION to be created, 
which makes sense because this function needs to use
an async task node instead(which has some added behaviour 
on being called such as actually activating the 
task, extra exec pins, etc). */
UFUNCTION(BlueprintCallable, Category = "Ability|Tasks", meta = (DisplayName = "ExecuteMyTask", HidePin = "OwningAbility", DefaultToSelf = "OwningAbility", BlueprintInternalUseOnly = "TRUE"))
static UAbilityTask_MyTask* CreateMyTask(UGameplayAbility* OwningAbility, FName TaskInstanceName, float examplevariable);
```

The cpp code is fairly straightforward, you simply create a task using the dedicated NewAbilityTask constructor function, initialize its values as you see fit and then return it. The blueprint node itself will usually do the rest of the job activating and keeping track of it, etc.:

```cpp
UAbilityTask_MyTask* UAbilityTask_MyTask::CreateMyTask(UGameplayAbility * OwningAbility, FName TaskInstanceName, float examplevariable)
{
    UAbilityTask_MyTask* MyObj = NewAbilityTask->UAbilityTask_MyTask->(OwningAbility, TaskInstanceName);
    //Just assume we have defined a float called OptionalValue somewhere in the class before. This is just an example.
    MyObj->OptionalValue = examplevariable;
    return MyObj;
}
```

Compile and, if everything has been done correctly, you should now have a new task function by the name of "ExecuteMyTask"(or your custom name) to use in your ability BPs. It doesn't have any new exec pins we could use though. Let us fix that!

While the exact logic behind how and why async task nodes work remain nebulous to me, creating new exec pins is actually rather easy in practice. First you need to define a dynamic multicast delegate. Multicast delegates are basically special structs you can wire functions into to call later upon "broadcasting" the delegate. These macros require a name for the new type of delegate you want to define, and they also need a list of parameter types and their corresponding names if your delegate is supposed to take functions that take at least one parameter themselves(as the delegate will then call these functions with the parameters it is broadcasted with). This all probably sounds very strange and complicated just written out like that, but it is actually rather easy when you see the code:

```cpp
//This lets you create a delegate with no parameters by the struct name of "FMyDelegate".
DECLARE_DYNAMIC_MULTICAST_DELEGATE(FMyDelegate);

//So if you want to have a class with a delegate variable of that type, you'd declare it as
FMyDelegate DelegateVariable;

//Finally, if you want to call all functions wired to DelegateVariable, you call
DelegateVariable.Broadcast();

/* You're not limited to just no-parameter functions either, a delegate 
that takes functions with a first parameter float and a second parameter int 
looks like this: */
DECLARE_DYNAMIC_MULTICAST_DELEGATE_TwoParams(FMyTwoParamDelegate, float, FirstParamName, int32, SecondParamName);

//You would then broadcast it like, for example:
TwoParamDelegateVariable.Broadcast(20.f, 15);
```

How does this detour help us? Simple, an async task node will look for the first UPROPERTY dynamic multicast delegate variable it finds in your AbilityTask class and use it as the delegate type for its extra outgoing exec pins from that point. Check out this code for example:

```cpp
DECLARE_DYNAMIC_MULTICAST_DELEGATE_TwoParams(FMyTwoParamDelegate, float, FirstParamName, int32, SecondParamName);
UCLASS()
class WIZARDMP_API UAbilityTask_MyTask : public UAbilityTask
{
    GENERATED_BODY()
    //The important bit here.
    UPROPERTY(BlueprintAssignable)
    FMyTwoParamDelegate OnCalled;

        UFUNCTION(BlueprintCallable, Category = "Ability|Tasks", meta = (DisplayName = "ExecuteMyTask", HidePin = "OwningAbility", DefaultToSelf = "OwningAbility", BlueprintInternalUseOnly = "TRUE"))
        static UAbilityTask_MyTask* CreateMyTask(UGameplayAbility* OwningAbility, FName TaskInstanceName, float examplevariable);

    /* This function will call after the BP node has successfully requested the 
    ability task from the static function. You put your actual 
    functionality here. More on that in a bit. */
    virtual void Activate() override;
};
```

The async node will now have a new outgoing exec pin labelled "OnCalled" right under its regular exec pin, and there will even be pins for a float and an int value right below said exec pin, which you may now use to decide further action with inside your ability BP!

Do note that you may only have one multicast delegate type as dedicated exec pin delegate. If you were to have multiple multicast delegate types used in your class, the first one takes priority and the variables using the other types will not show up! Henceforth you should make sure that your delegate covers the variable needs of all your possible output execution pins. Better to have a pin occassionally unused than not having enough to convey all the important info your ability may need.

Broadcasting the delegate variable will now also fire off the exec pin in the BP. Usually you will have a different function within your class that you can wire up to some kind of different delegate, TimerHandle or any similar thing so you can wait for a particular thing to happen before broadcasting your main delegate. Unfortunately this example has no actual usage scenario in mind, so we will simply just broadcast the delegate right in the Activate function instead:

```cpp
void UAbilityTask_MyTask::Activate()
{
    /* This is the part where you'd set up different delegates, timers etc. to prepare the task
    to eventually broadcast OnCalled sometime later. We have nothing prepared in this tutorial 
    task however, so we may as well just call OnCalled right within the Activate function instead. */
    OnCalled.Broadcast(500.f, 42);
}
```

With that, your first task should be complete! This example is quite barebones, but should showcase everything important you need to know when making your own, real task to use in conjunction with your own systems. In case you are still a bit unsure about certain things, you can use the folder with the ability tasks contained within the plugin itself for further directions and pointers on how to do certain things. Godspeed!

#### GameplayTasks Example

Here is an example Blueprint graph of using a `GameplayAbilityTargetActor_SingleLineTrace` to do a "hitscan"-type weapon. It fires a ray from the player's origin in the direction they're looking (handled by the GameplayTask). When it hits something, it reports back to the Blueprint graph. The Blueprint graph then draws a pink line based on the origin and ending points of the line trace and ends the ability.

![Hitscan Weapon](https://github.com/NickGlenn/Unreal-Engine-4-Community-Guide/tree/58f38c224a525dc8480d25ca361411d9d3e3ff4c/.gitbook/assets/gameplayabilitiesandyou/Hitscan_Weapon.png)

You could go farther and use the struct provided from the output of `GameplayAbilityTargetActor_SingleLineTrace` to determine which Pawn you hit (if any) and apply a **GameplayEffect** to it, reducing its health or applying buffs of some kind. Speaking of GameplayEffects...

### GameplayEffects

#### Overview

**GameplayEffects** can be described as this system's dedicated buff class. Their functionality goes a little beyond that, and in fact most stat modifiers regardless of instant and permanent or over time and temporary are usually GameplayEffects. They're very peculiar in how they are set up to work as they are built to be hyper-efficient to replicate/network in general.

As such GameplayEffects are, first and foremost, glorified struct-like data assets with in-blueprint inheritance and without the ability to change their variables during runtime, as they will often be passed by class reference alone. In fact, you will almost NEVER see a plain GameplayEffect being passed around in code and especially not in Blueprint. The tooltip says they're data-only, and they really do mean that.

GameplayEffects usually use `GameplayEffectSpecs` to move around, which are huge behemoths of structs that store everything from effect context (what level, who is instigator, who is target, which ability spawned me, why do I even exist?) to reference to the GameplayEffect class that defines most default behaviour and variables to stack count to potential extra modifiers/tags/whatever to pass in alongside what the class reference defines upon applying. In a strange sort of way, `GameplayEffectSpecs` are much closer to object instances than the GameplayEffect instances themselves are. As such, if you want to apply a gameplay effect via ability, either apply it directly through a class reference or create a `GameplayEffectSpec` within the ability and use that to apply a GameplayEffect.

**Notable Variables** Due to the unusual nature of Gameplay Effect blueprint classes, most of their variables are either simple values, other direct class references or just tags. There are too many to list and after explaining how abilities and their tags work, it should be fairly self-explanatory what most tags are used for, or do. It should however be noted that Gameplay Effects have 3 containers for each type of tag, one that is not directly editable, one that describes tags added on top of tags potentially owned from a parent and tags that are removed from a potential parent. Basically, this tag inheritance setup is one of relatively few reasons why Gameplay Effects are full-fledged UObject classes in the first place. Some of the more notable variables are:

* **Duration Policy:** Is the effect instant, does it have a fixed duration, or does it go on infinitely? Do note that instant effects turn modifiers into permanent stat changes, and executions will be triggered immediately.

  Modifiers: Stat changes in all shapes and forms. Whether you want to add a flat amount to a stat, multiply a stat, divide, override with a fixed value or do any of these things in relation to other stats.
* **Executions:** Executions are an interesting case: They are essentially the functions the gameplay effect itself can't have (due to being meant to be as data-only as possible). An Execution takes a GameplayEffectExecutionCalculation as parameter, a class that is set up to define attributes to capture from both target and source, and to do things with them that would be considered too complex with modifiers alone. They are more or less meant to do as they please, however they cannot listen to events and such like abilities can do and pretty much only run in fixed, predefined intervals on timed GameplayEffects (and optionally once on application), or immediately on application in the case of instant GameplayEffects. They're your go-to for complex damage calculation and the likes. More on that later.
* **Stacking:** You know how in some games certain buffs/debuffs of one kind can stack on a target? This behaviour is managed here. By default all GameplayEffects of the same type will act and tick down independently (though requesting the amount of stacks of a gameplay effect will usually still show the total amount of effect instances of this type). There are options to make them all go on the same timer, removing one stack each time duration runs out, removing all of them once the timer runs out once, if application of a new stack refreshes the current duration or if there is a cap on stacks. You can get quite creative with these.
* **Overflow:** Adding up on stacks, overflow effects are essentially effects that the affected actor will be affected by when the max amount of stacks of this gameplay event has been reached. If you get cold enough you freeze, breathe enough poison gas to get heavily poisoned, whatever, you get it.
* **Display:** You can define GameplayCues to use here. At their most basic, GameplayCues are essentially visual/audible effects that respond to a specialized tag they've been assigned to. It needs to have "GameplayCue" as its parent tag, so an example tag could be "GameplayCue.DoT.Fire". You can call these directly in abilities too. They're a network-friendly way to spawn stuff like particle effects, cosmetic meshes and sound effects to provide your debuffs and skills with some eye candy. How they react to being called by the GameplayEffect/Ability is defined within the GameplayCue itself (there's 4 types of events a GameplayCue will respond to: OnActive (Called when a GameplayCue is activated), WhileActive (Called when GameplayCue is active, even if it wasn't actually just applied, eg. Join in progress), Removed (when... well, removed) and Executed (This will be called when a GameplayEffect's execute classes run via instant effects or periodic tick).
* **GrantedAbilities:** This has many uses. You may use a buff to temporarily provide an active ability as part of the buff(maybe a fire mage can give someone else a fire ability by igniting one of his allies? Heh, gotta love combat arson), but, more importantly, you can use these for effects that are too specific for modifiers but need to be permanently active in a way effect executions can't. If a gameplay effect is tagged to grant an actor an "OnFire" tag, you may have an ice buff with a passive ice ability granted listen for this event and remove the offending effect, as well as the ice buff itself (GameplayAbilities have a function just to allow them to remove the effect that granted them). Together with modifiers and executions, this allows you to do virtually anything with your effects.

It should be noted that most float values put into are not actually just plain float values, but rather a struct called **FScalableFloat**. You can use it just like any regular float, but there is an asset pointer to the right of the box where you'd put the float value in. It may confuse you because there are no valid references to use, and there is no option to create a new one. This slot is reserved for a **Curve Table**, an asset you get by importing a csv, or file with a comparable table file format, into the project.

***This is one of the few things where effect level makes a difference***, as the table will then look at the column labelled with this level (or the columns it should be between, determining the value dependent on what kind of graph the table row is set to describe) so if you use levels in, for example, your GameplayEffectExecutionCalculations, keep that in mind, as you may accidentally set a value to scale in unexpected ways otherwise.

#### GameplayEffects Example

Let's make an example of perhaps the simplest use case for GameplayEffects: Cooldowns. Below, we have a very simple GameplayAbility that prints "Hello", puts itself on cooldown, then ends the ability.

![Cooldown Ability](https://github.com/NickGlenn/Unreal-Engine-4-Community-Guide/tree/58f38c224a525dc8480d25ca361411d9d3e3ff4c/.gitbook/assets/gameplayabilitiesandyou/CooldownAbility.png)

The part circled in blue is the GameplayEffect which signals that we are on cooldown. When this GameplayEffect is applied to us, the ability is unusable.

The part circled in red is the GameplayEffect that gets applied to us when we use this ability. In this example, it's just something that puts us on cooldown right away, but we could make it so using an ability slows us down for a little bit, or starts stacking GameplayEffects until we reach a maximum amount, at which point another GameplayEffect is applied which causes us to actually go on cooldown (which could be a simple example of using GameplayAbilities for a weapon/ammo system).

Now we move on to the GameplayEffect itself.

![Cooldown Gameplay Effect](https://github.com/NickGlenn/Unreal-Engine-4-Community-Guide/tree/58f38c224a525dc8480d25ca361411d9d3e3ff4c/.gitbook/assets/gameplayabilitiesandyou/CooldownGameplayEffect.png)

The part in red sets this to be a GameplayEffect which happens over a duration (5 seconds in this example). At the end of this duration, the GameplayEffect is lifted. That's all this example does; it just applies itself for 5 seconds.

The part in blue is where all the magic happens. An FGameplayTag "AbilityTags.Cooldown" is applied to our AbilitySystemComponent while this GameplayEffect is active. This is how our AbilitySystemComponent knows which GameplayEffects are active. When you try to activate the sample GameplayAbility above, it checks to see if you have the tags in blue. If you do, then nothing happens -- it won't let you activate the ability. Otherwise, the ability works. The tags in there can be called whatever you want; these ones just happen to be called "`AbilityTags.Cooldown`".

#### AttributeSet

**AttributeSets** are thankfully very simple to explain. They define float values (and ONLY float values. Right now only float attributes are supported) and can be connected to AbilitySystems to grant the ability system in question these attributes. GameplayEffects and GameplayEffectExecutionCalculations have specifically designed macros and menus to manipulate these attributes on an ability system. An ability system may use multiple attribute sets or none at all, too.

The system accounts for attributes it cannot find and will simply ignore stats that are not appropriate for the particular actor and his AbilitySystem. As such, maybe both players and foes have Health, Mana, attack damage, defense, you name 'em, and players then have an extra attribute set containing RPG attributes such as Strength, Intelligence, Constitution and the like. These are all perfectly possible scenarios, and it's nice that the system gives you the option to mix and match multiple attribute sets. The best way to bind an attribute set to an ability system is to create the AttributeSet as the same actor's subobject in the constructor. The ability system should find it by itself. It does for me, at least.

Attributes within attribute sets are defined like any other UPROPERTY, which is amazingly practical and straightforward. Why can't everything in this module be... Well, it isn't that easy anyway, due to the AttributeSet's functions, which either deal with finding out which UPROPERTY the current parameter is talking about or have to do with the infinitely more complex GameplayEffectExecutionCalculation.

**PreAttributeBaseChange** is called before... well, an attribute's base value (so without any temporary modifiers) is changed. It would be unwise to use this for game logic, and is mostly there to allow you to describe stat clamping.

**PreAttributeChange** is in the same boat, but here you can define clamping with temporary modifiers instead. Either way, NewValue describes the new value of a changed stat, and FGameplayAttribute Attribute describes some info about the stat we're talking about. If you want to find out if this particular Attribute change is talking about a particular Attribute MyAttribute in UMyAttributeSet, you'd do it something like this:

```cpp
Attribute.GetUProperty() == FindFieldChecked<UProperty>(UMyAttributeSet::StaticClass(), GET_MEMBER_NAME_CHECKED(UMyAttributeSet, MyAttribute))
```

This code takes the UPROPERTY variable of the Attribute parameter and checks if the referenced UPROPERTY is identical with the one that describes MyAttribute in UMyAttributeSet. The macro is mostly there for safety, I believe this is actually defined as a relatively simple string.

**PreGameplayEffectExecute** is a function that takes the data a GameplayEffectExecutionCalculation spits out (including which stats it wishes to modify, and by how much), and can then decide if the GameplayEffectExecutionCalculation is allowed to influence the AttributeSet in any way, by returning an appropriate bool. PostGameplayEffectExecute happens after this evaluation and as such you are unable to throw the GameplayEffectExecution out properly by then. However, because 90% of the time things such as damage calculations will be effect executions, here will be an excellent place to wrap such a thing up, such as by, for example, checking if the damage you took killed you.

#### Using AttributeSets

So, now that we understand what Attributes are and how they work, let's take a look at a simple "Health" attribute.

This is some simple code, which just gives an AbilitySystemComponent a "Health" value:

```cpp
UCLASS()
class UMyAttributeSet : public UAttributeSet
{
    GENERATED_BODY()
public: 
//Hitpoints. Self-explanatory.
UPROPERTY(Category = "Wizard Attributes | Health", EditAnywhere, BlueprintReadWrite)
FGameplayAttributeData Health;

//FGameplayAttributeData is the intended struct to be used for attributes by the system. However,
//attributes can also be declared as simple floats. I am unsure if the attribute initialization method
//further down functions with the struct, however the float method seems to be the more dated one.

}
```

That's it! Easy, right?

But as of right now, that health value doesn't do anything. You can tell the ability system that you have some health, but it doesn't know what to do when your health hits 0 (and indeed, in the above example, your health IS 0 -- you might want to add a constructor or something to set it to a reasonable value). That's where the functions like PostGameplayEffectExecute that we just learned about come into play!

Here's some code taken from Dave Ratti's example GitHub project linked at the beginning of the article:

```cpp
void UGASAttributeSet::PostGameplayEffectExecute(const struct FGameplayEffectModCallbackData& Data)
{
    UAbilitySystemComponent* Source = Data.EffectSpec.GetContext().GetOriginalInstigatorAbilitySystemComponent();
    if (HealthAttribute() == Data.EvaluatedData.Attribute)
    {
        // Get the Target actor
        AActor* DamagedActor = nullptr;
        AController* DamagedController = nullptr;
        if (Data.Target.AbilityActorInfo.IsValid() && Data.Target.AbilityActorInfo->AvatarActor.IsValid())
        {
            DamagedActor = Data.Target.AbilityActorInfo->AvatarActor.Get();
            DamagedController = Data.Target.AbilityActorInfo->PlayerController.Get();
        }
        // Get the Source actor
        AActor* AttackingActor = nullptr;
        AController* AttackingController = nullptr;
        AController* AttackingPlayerController = nullptr;
        if (Source && Source->AbilityActorInfo.IsValid() && Source->AbilityActorInfo->AvatarActor.IsValid())
        {
            AttackingActor = Source->AbilityActorInfo->AvatarActor.Get();
            AttackingController = Source->AbilityActorInfo->PlayerController.Get();
            AttackingPlayerController = Source->AbilityActorInfo->PlayerController.Get();
            if (AttackingController == nullptr && AttackingActor != nullptr)
            {
                if (APawn* Pawn = Cast<APawn>(AttackingActor))
                {
                    AttackingController = Pawn->GetController();
                }
            }
        }
        // Clamp health
        Health = FMath::Clamp(Health, 0.0f, MaxHealth);
        if (Health <= 0)
        {
            // Handle death with GASCharacter. Note this is just one example of how this could be done.
            if (AGASCharacter* GASChar = Cast<AGASCharacter>(DamagedActor))
            {
                // Construct a gameplay cue event for this death
                FGameplayCueParameters Params(Data.EffectSpec.GetContext());
                Params.RawMagnitude = Data.EvaluatedData.Magnitude;
                Params.NormalizedMagnitude = FMath::Abs(Data.EvaluatedData.Magnitude / MaxHealth);
                Params.AggregatedSourceTags = *Data.EffectSpec.CapturedSourceTags.GetAggregatedTags();
                Params.AggregatedTargetTags = *Data.EffectSpec.CapturedTargetTags.GetAggregatedTags();
                GASChar->Die(DamagedController, DamagedActor,  Data.EffectSpec, Params.RawMagnitude, Params.Normal);
            }
        }
    }
}
```

You can see how things start getting a little more complex, but really, it's nothing you can't handle! `HealthAttribute()` is defined using that same macro we used earlier:

```cpp
FGameplayAttribute UGASAttributeSet::HealthAttribute()
{
    static UProperty* Property = FindFieldChecked<UProperty>(UGASAttributeSet::StaticClass(), GET_MEMBER_NAME_CHECKED(UGASAttributeSet, Health));
    return FGameplayAttribute(Property);
}
```

#### Data-driven Initialization of Attributes

One way to initialize your attributes is to use a data table. You can create a .csv file in the following format and when importing, select "Attribute Meta Data" as the row type. The name column is a little tricky here: you have to use your class name without the 'U' in front, so MyAttributeSet instead of UMyAttributeSet.

| Name                                                      | BaseValue | MinValue | MaxValue | DerivedAttributeInfo | bCanStack |   |   |   |     |   |     |
| --------------------------------------------------------- | --------- | -------- | -------- | -------------------- | --------- | - | - | - | --- | - | --- |
|                                                           |           | x        |          | y                    |           | z |   |   | ??? |   | T/F |
| MyAttributeSet.Movespeed    300    0    1000        FALSE |           |          |          |                      |           |   |   |   |     |   |     |

| Name                                   | BaseValue | MinValue | MaxValue | DerivedAttributeInfo | bCanStack |
| -------------------------------------- | :-------: | :------: | :------: | :------------------: | :-------: |
| *\[YourAttrClass].\[YourAttrProperty]* |    *x*    |    *y*   |    *z*   |         *???*        |   *T/F*   |
| MyAttributeSet.Movespeed               |    300    |     0    |   1000   |                      |   FALSE   |

Next, add a property in your character to hold a pointer to this table. Make sure to assign your table to this pointer, whether through blueprints or C++:

```cpp
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = Abilities)
UDataTable* AttrDataTable;
```

Somewhere after you create your AbilitySystemComponent, like at the end of BeginPlay(), you can read in the table. It's a simple one-liner:

```cpp
if (AbilitySystem && AttrDataTable) { const UAttributeSet * Attrs = AbilitySystem->InitStats(UMyAttributeSet::StaticClass(), AttrDataTable); }
```

If you setup your table correctly, your stats should be initialized properly!

#### Replication

In the case of a multiplayer game, attributes must usually still be replicated. You replicate them like any other C++ variable, by including the UnrealNetwork.h in your header, adding a "Replicated" tag inside the variable UPROPERTY macro and overriding void GetLifetimeReplicatedProps(TArray& OutLifetimeProps) const so that the variable is properly included as replicated variable.

However, the system requires some extra replication parameters that the normal DOREPLIFETIME macro does not set properly. As such, we need to use a macro which has more parameters, and set these accordingly. It's thankfully quite simple, as all attributes will use the same settings.

```cpp
void UWizardAttributeSet::GetLifetimeReplicatedProps(TArray< FLifetimeProperty > & OutLifetimeProps) const
{
    Super::GetLifetimeReplicatedProps(OutLifetimeProps);

    //DOREPLIFETIME( UMyAttributeSet, MyAttribute); Chances are this is how you would ordinarily do it, however in the case of attributes this'll lead to confusing and annoying replication errors, usually involving clientside ability prediction. 
    DOREPLIFETIME_CONDITION_NOTIFY( UMyAttributeSet, MyAttribute, COND_None, REPNOTIFY_Always); //This is how it is done properly for attributes. }
```

However, attributes need some extra legwork so that values and structs depending on this attribute in question get changed according to a value a client receives from the server. We need to replace the "Replicated"-tag in your UPROPERTY with a "ReplicatedUsing=OnRep\_MyFunction" tag, with OnRep\_MyFunction being the function you wish to call to update your current attribute. Functionally this means each attribute needs its own OnRep function, like so:

```cpp
UPROPERTY(Category = "Attribute", EditAnywhere, ReplicatedUsing = OnRep_MyAttribute, BlueprintReadWrite)
float MyAttribute;

UFUNCTION()
void OnRep_MyAttribute()
{
    GAMEPLAYATTRIBUTE_REPNOTIFY(UMyAttributeSet, MyAttribute);
}
```

### The More Advanced Nitty Gritty

So we have Abilities, Attributes and Effects now. Cool. However, with the tools we have currently introduced, it is difficult to really tie the individual components of this system into each other: Abilities can be called remotely, but only when tags are/have been granted to their owner and without any parameters to work with, GameplayEffects are severely limited by modifiers being so basic and abilities requiring explicit outside triggers to really do anything, and Attributes... well, those are actually working just fine considering they're just float containers at heart, but accessing them and setting up global calculations with them could be easier.

Anyhow, GameplayEvents and GameplayEffectExecutionCalculations are there to really tie up the loose ends of the system together and really make a proper package out of the single excellent systems we have right now.

#### GameplayEffectExectutionCalculation

To put it simply, a **GameplayEffectExecutionCalculation** is a function a GameplayEffect may have and may call in fixed intervals over the effect's duration and/or during initial application. They can do whatever they want really as their Execute function provides them with all parameters necessary to influence their respective actor, ability system or even outside world directly, but due to being a little inconvenient to set up, being C++ only for the moment and lacking any real way to react to the outside world in the way Abilities can, you may be better off with Abilities instead depending on what you want to do.

However, an GameplayEffectExecutionCalculation's unique gimmick is that it can capture attributes from both Source of the GameplayEffect and Target of the GameplayEffect while applying a modifier to them just for this function activation, and use them as parameters of sorts for the calculation, being also able to snapshot particular attributes when the GameplayEffect is first conceived if such a thing would be necessary (for instance, you can attach a GameplayEffectSpec to a fireball projectile, applying it to whoever gets hit, and the fireball naturally shouldn't be influenced by damage boosts and changes on the source once it has initially been fired). This makes GameplayEffectExecutionCalculations amazingly useful for things such as global damage calculations, which will also be our go-to example to understand the setup with in this guide. It will be a very simple and naively implemented example, but it will help you set up a more complex one.

For starters, assume that we have an arbitrary attribute system possessing the following attributes: Health, AttackMultiplier and DefenseMultiplier. Health will decrease as damage is taken (I mean, obviously), AttackMultiplier multiplies outgoing damage with itself and DefenseMultiplier will multiply incoming damage with itself (usually being below 1, or 100%, essentially reducing incoming damage).

I will assume that you will have experimented with the system and the examples in the previous section already and can just add these to your other attributes if you do not already possess similar ones. Just in case, the code of an attribute system with just these values could look a little like this:

```cpp
UCLASS()
class UMyAttributeSet : public UAttributeSet 
{
    GENERATED_BODY()

public:
    //Hitpoints. Self-explanatory.
    UPROPERTY(Category = "Wizard Attributes | Health", EditAnywhere, BlueprintReadWrite)
    FGameplayAttributeData Health;

    //Outgoing damage-multiplier.
    UPROPERTY(Category = "Wizard Attributes | Health", EditAnywhere, BlueprintReadWrite, meta = (HideFromModifiers))
    FGameplayAttributeData AttackMultiplier;

    //Incoming damage-multiplier.
    UPROPERTY(Category = "Wizard Attributes | Health", EditAnywhere, BlueprintReadWrite)
    FGameplayAttributeData DefenseMultiplier;

}
```

However, we actually want to add another attribute on top of that.

Because a GameplayEffectExecutionCalculation takes attributes as pseudo-parameter, we want an extra attribute just so we may define an effect's base damage. We could combine AttackMultiplier and BaseAttackPower into one attribute, but you may get into deep feces once you want to add buffs that influence your outgoing damage, and simply adding values to your BaseAttack may have quite notable balance implications and such if you have a rapid-fire ability that deals a lot of very small damage effects. You COULD change BaseAttack for some buffs and effects, but that's mostly you and your game's call. Basically, having a percentage multiplier on top of a flat attack value is probably a better idea.

Anyhow, you should add BaseAttackPower as an attribute.

```cpp
UCLASS()

class UMyAttributeSet : public UAttributeSet
{
    GENERATED_BODY()
public:
    //Hitpoints. Self-explanatory.
    UPROPERTY(Category = "Wizard Attributes | Health", EditAnywhere, BlueprintReadWrite)
    FGameplayAttributeData Health;

    //Outgoing damage-multiplier.
    UPROPERTY(Category = "Wizard Attributes | Health", EditAnywhere, BlueprintReadWrite, meta = (HideFromModifiers))
    FGameplayAttributeData AttackMultiplier;

    //Incoming damage-multiplier.
    UPROPERTY(Category = "Wizard Attributes | Health", EditAnywhere, BlueprintReadWrite)
    FGameplayAttributeData DefenseMultiplier;

    //Base damage of an outgoing attack.
    UPROPERTY(Category = "Wizard Attributes | Health", EditAnywhere, BlueprintReadWrite)
    FGameplayAttributeData BaseAttackPower;
}
```

Alright, so we got all our important attributes set up, it's time to create a new GameplayEffectExecutionCalculation. Go to your C++ folder in your content explorer, click New C++ class, select GameplayEffectExecutionCalculation as your parent, and select a name for your new class that doesn't take half a decade to pronounce or type. I am calling mine DamageExec. You may do too, if you like.

Once it has finished compiling, you want to change GENERATED\_BODY() at the top of your class declaration in your header to GENERATED\_UCLASS\_BODY(). This way, Unreal's preprocessor-generation-thingie will define us a constructor DamageExec(const FObjectInitializer& ObjectInitializer). We want to implement it in our cpp file like so.

```cpp
UDamageExecution::UDamageExecution(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
{

}
```

We will actually need to do a few things in our constructor, namely giving the Execution info on what attributes we wish to capture from whom. We will need FGameplayEffectAttributeCaptureDefinitions for this. Thankfully, the module has macros for these that makes it easy to set them up.

For the sake of simplicity (as we will need the definitions and UPROPERTYs of our attributes in different functions), we will put these in a struct.

```cpp
struct AttStruct
{
    //The DECLARE_ATTRIBUTE_CAPTUREDEF macro actually only declares two variables. The variable names are dependent on the input, however. Here they will be HealthProperty(which is a UPROPERTY pointer)
    //and HealthDef(which is a FGameplayEffectAttributeCaptureDefinition).
    DECLARE_ATTRIBUTE_CAPTUREDEF(Health);

    DECLARE_ATTRIBUTE_CAPTUREDEF(AttackMultiplier); //Here AttackMultiplierProperty and AttackMultiplierDef. I hope you get the drill.
    DECLARE_ATTRIBUTE_CAPTUREDEF(DefenseMultiplier);
    DECLARE_ATTRIBUTE_CAPTUREDEF(BaseAttackPower);

    AttStruct()
    {
        // We define the values of the variables we declared now. In this example, HealthProperty will point to the Health attribute in the UMyAttributeSet on the receiving target of this execution. The last parameter is a bool, and determines if we snapshot the attribute's value at the time of definition.
        DEFINE_ATTRIBUTE_CAPTUREDEF(UMyAttributeSet, Health, Target, false);

        //This here is a different example: We still take the attribute from UMyAttributeSet, but this time it is BaseAttackPower, and we look at the effect's source for it. We also want to snapshot is because the effect's strength should be determined during its initial creation. A projectile wouldn't change
        //damage values depending on the source's stat changes halfway through flight, after all.
        DEFINE_ATTRIBUTE_CAPTUREDEF(UMyAttributeSet, BaseAttackPower, Source, true);

        //The same rules apply for the multiplier attributes too.
        DEFINE_ATTRIBUTE_CAPTUREDEF(UMyAttributeSet, AttackMultiplier, Source, true);
        DEFINE_ATTRIBUTE_CAPTUREDEF(UMyAttributeSet, DefenseMultiplier, Target, false);
    }
};
```

Now we have a struct that contains the CaptureDefinitions we need, so in the constructor we can simply write:

```cpp
UDamageExec::UDamageExec(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
{
    AttStruct Attributes;

     RelevantAttributesToCapture.Add(Attributes.HealthDef); //RelevantAttributesToCapture is the array that contains all attributes you wish to capture, without exceptions. 
     InvalidScopedModifierAttributes.Add(Attributes.HealthDef); //However, an attribute added here on top of being added in RelevantAttributesToCapture will still be captured, but will not be shown for potential in-function modifiers in the GameplayEffect blueprint, more on that later.

     RelevantAttributesToCapture.Add(Attributes.BaseAttackPowerDef);
     RelevantAttributesToCapture.Add(Attributes.DefenseMultiplierDef);
     RelevantAttributesToCapture.Add(Attributes.AttackMultiplierDef);
}
```

Compile, and voilà, it should now successfully capture attributes. You may check by opening up a GameplayEffect blueprint, and trying to select DamageExec as Execution class. It should allow you to view and select a few more settings. Add a new element in the array CalculationModifiers, and you should see BaseAttackPower, DefenseMultiplier and AttackMultiplier as valid Backing Capture Definition (not Health, however, as you have rendered it as hidden by adding it to `InvalidScopedModifierAttributes`). These are these calculation-only modifiers I talked about. Basically, you can now easily define each gameplay effect's BaseAttackPower individually by adding/setting BaseAttackPower to a value of choice.

Well, but that wouldn't really do anything right now. We have set up capture definitions, but we haven't really set up any functionality. Declare the function `virtual void Execute_Implementation(const FGameplayEffectCustomExecutionParameters& ExecutionParams, OUT FGameplayEffectCustomExecutionOutput& OutExecutionOutput) const override` in your header, and create a fitting definition in your cpp file.

I will just copy-paste an excerpt from Dave's damage calculation from the example project mentioned in this wiki's introduction, and will add comments and changes where appropriate for our level of wisdom and our current setup of attributes.

```cpp
void UDamageExec::Execute_Implementation(const FGameplayEffectCustomExecutionParameters & ExecutionParams, OUT FGameplayEffectCustomExecutionOutput & OutExecutionOutput) const
</pre>
{
    AttStruct Attributes; //Creating the attribute struct, we will need its values later when we want to get the attribute values.

    UAbilitySystemComponent* TargetAbilitySystemComponent = ExecutionParams.GetTargetAbilitySystemComponent(); //We put AbilitySystemComponents into little helper variables. Not necessary, but it helps keeping us from typing so much.

    UAbilitySystemComponent* SourceAbilitySystemComponent = ExecutionParams.GetSourceAbilitySystemComponent();

    AActor* SourceActor = SourceAbilitySystemComponent ? SourceAbilitySystemComponent->AvatarActor : nullptr; //If our AbilitySystemComponents are valid, we get each their owning actors and put them in variables. This is mostly to prevent crashing by trying to get the AvatarActor variable from

    AActor* TargetActor = TargetAbilitySystemComponent ? TargetAbilitySystemComponent->AvatarActor : nullptr; //a null pointer.

    const FGameplayEffectSpec & Spec = ExecutionParams.GetOwningSpec();
    const FGameplayTagContainer* SourceTags = Spec.CapturedSourceTags.GetAggregatedTags();
    const FGameplayTagContainer* TargetTags = Spec.CapturedTargetTags.GetAggregatedTags(); //Some more helper variables: Spec is the spec this execution originated from, and the Source/TargetTags are pointers to the tags granted to source/target actor, respectively.

    FAggregatorEvaluateParameters EvaluationParameters; //We use these tags to set up an FAggregatorEvaluateParameters struct, which we will need to get the values of our captured attributes later in this function.

    EvaluationParameters.SourceTags = SourceTags;
    EvaluationParameters.TargetTags = TargetTags;

    float Health = 0.f;

    //Alright, this is where we get the attribute's captured value into our function. Damage().HealthDef is the definition of the attribute we want to get, we defined EvaluationParameters just above us, and Health is the variable where we will put the captured value into(the Health variable we just declared)
    ExecutionParams.AttemptCalculateCapturedAttributeMagnitude(Attributes.HealthDef, EvaluationParameters, Health); 

    float BaseAttackPower = 0.f;
    ExecutionParams.AttemptCalculateCapturedAttributeMagnitude(Attribute.BaseAttackPowerDef, EvaluationParameters, BaseAttackPower); // We do this for all other attributes, as well.

    float AttackMultiplier = 0.f;
    ExecutionParams.AttemptCalculateCapturedAttributeMagnitude(Attribute.AttackMultiplierDef, EvaluationParameters, AttackMultiplier);

    float DefensePower = 0.f;
    ExecutionParams.AttemptCalculateCapturedAttributeMagnitude(Attribute.DefenseMultiplierPowerDef, EvaluationParameters, DefenseMultiplier);

    //Finally, we go through our simple example damage calculation. BaseAttackPower and AttackMultiplier come from soruce, DefensePower comes from target.
    float DamageDone = BaseAttackPower * AttackMultiplier * DefensePower;

    //An optional step is to clamp to not take health lower than 0. This can be ignored, or implemented in the attribute sets' PostGameplayEffectExecution function. Your call, really.
    DamageDone = FMath::Min<float>( Damage, Health );

    //Finally, we check if we even did any damage in this whole ordeal. If yes, then we will add an outgoing execution modifer to the Health attribute we got from our target, which is a modifier that can still be thrown out by the attribute system if it wishes to throw out the GameplayEffectExecutionCalculation.
    if (DamageDone > 0.f)
    {
        OutExecutionOutput.AddOutputModifier(FGameplayModifierEvaluatedData(Damage().HealthProperty, EGameplayModOp::Additive, -DamageDone));
    }
    //Congratulations, your damage calculation is complete!
}
```

With that, your new damage calculation is now complete. You are free to try to use it through an instant GameplayEffect of choice. Set up a widget or debug string somewhere to tell you your current HP, set the BaseAttackPower of your GameplayEffect's execution to something high like 100, do not forget to assure that the multiplier attributes are not 0, and if your effect reduces your HP, then congrats! You got your very first damage execution calculation running!

You can expand it as you please, as the ExecutionParams parameter of your Execute contains all info about your target, source and GameplayEffectSpec. Want to multiply your damage by your GameplayEffectSpec's level? Easily done. Have an if-statement somewhere that says "if the target actor has tag X that is described to grant him immunity to all damage, reduce the damage of this calculation to 0" if you need such a thing for your game.

It is easy to extend this damage calculation once you get it running initially. Add new multiplier attributes for fire or ice or whatever damage, and have it so that your execution checks for tags on either the source or the EffectSpec itself that say whether to consider these or not. Be creative! You have the tools, you have the power!

An aspect I forgot to mention, and that doesn't quite fit into this example, is that calculations can be used to decide if conditional gameplay effect classes attached to a particular gameplay effect should be applied upon calling of the execution, calling the function MarkConditionalGameplayEffectsToTrigger() from the Execute\_Implementation function's parameter OutExecutionOutput.

For example, you may use calculations to determine if the user's health is below half their maximum health, and call a GameplayEffect granting them a stats buff accordingly. It can be as simple as a simple stat check to as elaborate as a calculation that refuses to apply the conditional GameplayEffect without a certain effect asset tag while applying copies of the owning gameplay effect with this asset tag, simulating an aura-effect that doesn't affect the owner with just a GameplayEffectExecution alone (this example is a little out there, though. Cut me some slack, thinking off a usage example for every other aspect of the system is hard).

Another thing to keep in mind is that executions are not set up to predictively run for a client. As such, their effects will only show themselves to the causing actor when the server receives it.

### Gameplay Events

Alright, this should about be the last major component of the system we haven't extensively talked about. Gameplay Events are amazingly useful due to their ability to trigger abilities without messing around with the ability owner's tags, while at the same time providing the GameplayAbility in question with a useful payload that may contain the source, target actors, magnitude and even generic object pointers for abilities to use as parameter. They're great if you have generic events and situations many abilities will call or listen for. A damage execution may for example throw out a GameplayEvent before damage is applied so that abilities can react with damage-decreasing buffs or pre-damage heals, and one after all multipliers and reductions so that abilities can take the final damage done to, for example, heal the source in proportion to the dealt damage (which would be a simple implementation for lifesteal). Gameplay Events are amazingly flexible, and most kinds of reactionary passive abilities can be implemented with well-implemented Gameplay Events in globally used functions and executions.

You don't really create a new GameplayEvent in the same way you create a new class. They're in fact just mere data structs, and use a tag to tell abilities what kind of event they are. It is up to the abilities themselves to react to them appropriately.

The struct responsible for GameplayEvents, the `FGameplayEventData`, has the following variables:

* **EventTag:** The tag that the event uses as label to be identified by. Do note that an event with tag label X will NOT actually call all GameplayAbilities using this tag as trigger. More on that later.
* **Instigator:** An actor pointer to point to the source or instigator with. Due to the nature of events, you can place any actor reference here, or even leave it null, but it never hurts to put a fitting actor reference here.
* **Target:** Same as instigator, but for targets. Personally, I always set this to the actor we call the gameplay event for, because, I mean, that IS pretty much the target of the GameplayEffect. That said, if you for example have an event that tells a damage source it dealt damage to a target, you can switch it around like that too. It's your call, you are given pretty much no limits or guidelines in this struct.
* **OptionalObject** and **OptionalObject2:** UObject pointers that can be filled with references for extra info. Maybe you want a GameplayEvent in your own child, or maybe a GameplayAbility you inherit all your other spells from that implements at the initial activation, taking the GameplayAbility object itself as parameter.
* **ContextHandle:** GameplayEffectContextHandles are the part of effect specs that store the origin of an effect, such as the ability they came from, the original creation point in the world, the owner of the effect. These all can be useful for the GameplayEvent itself, so add this parameter when you can.
* **InstigatorTags**, **TargetTags:** The tags the instigator and target had during the initial calling of the GameplayEvent. This is different from getting the tags through the instigator/target pointers, as the tag containers through the pointers may update halfway through (obviously, due to being pointers).

These are not actually unused as it turns out, as abilities called with the payload will run these tags through its Source/Target Required/Blocked tags, so if you wish to use these features that are built into every ability by default, you should set the tags accordingly. Also worth noting is that the code doesn't check if any rules are held up though, so it's up to you how you ultimately wish to fill these out. Whether you simply pass the tags currently applied to your target and instigator actors to these containers, whether you opt to fill the containers with tags further describing the situation or a different alternative is all up to you.

* **EventMagnitude:** A singular float. You're more or less free to use it as you want. I personally use it as parameter for my damage events, setting the magnitude to the calculated damage up to the particular step in the calculation (I have an event before all calculations, after bonus multipliers, after resistances, etc.). This is just an example, though.

GameplayEvent structs do not have a constructor that parametrizes these, so you need to set these manually. A little annoying, but you can set up functions to help with that.

Alright, now that we have a GameplayEvent struct, it's time to trigger abilities with it. Abilities may set up a trigger by going to their class defaults and adding a trigger with trigger source Gameplay Event and your tag of choice as values.

We actually can go two different paths to call a GameplayEvent for all abilities in an ability system component:

* We may call the static function `SendGameplayEventToActor(AActor* Actor, FGameplayTag EventTag, FGameplayEventData Payload)` from the `AbilitySystemBlueprintLibrary` class (which is pretty much just one big class of convenience methods exposed to blueprints)
* We may also call the ability system component's `HandleGameplayEvent(FGameplayTag EventTag, const FGameplayEventData* Payload)` function directly.

AbilitySystemBlueprintLibrary's function is safer and more convenient to use, though our actor needs the `IAbilitySystemInterface` implemented for it to work properly. It also does not return the amount of abilities that got triggered by the particular EventTag we use as parameter, though chances are most abilities and systems will very rarely need it. As such, using AbilitySystemBlueprintLibrary's function is often a better idea

Either way, the meaningful parameters of both functions boil down to an FGameplayTag EventTag and the GameplayEvent struct itself, which is usually called Payload. The Payload is self-explanatory, as this is what we will give our ability to work with when called from GameplayEvent. The EventTag is the tag that the ability system component to try to trigger all abilities by. This tag and the tag you give to the struct as label must not be the same thing. For my own usage they usually are, but nothing stops you from having separate tags for event calling and tags for event labelling.

Alright, so if you did everything correctly, your ability should respond to a GameplayEvent of choice (this is easily testable by assigning a random key input on your character to send the event with the event tag of choice to your character, as it should have implemented the interface a long time ago by now).

That's fine and dandy, but where is the payload? Well, going back to the GameplayAbility blueprint for a little, you may or may not have noticed already that there is a different ActivateAbilityEvent defined, but not added to the event graph by default. The event is called ActivateAbilityFromEvent, which does have a Gameplay Event data struct as input.

Your first thought may be to set up a separate chain of blueprint nodes that start from the ActiveAbilityFromEvent node, but this is wrong. The reason for this is not at all simple and in fact rather bizarre, because GameplayAbility's constructor is set in such a way that **it will set a hidden bool to use the struct-less ActivateAbility node for all ability activations when it is present in the blueprint graph of an inherited blueprint class.** I told you man, witchcraft! This module is witchcraft!

Essentially, you will have to replace the `ActivateAbility` node with the Event activation event in your GameplayAbility blueprint. This surrenders your ability to call your ability through conventional means which does not provide the ability with a Gameplay Event struct to work with (such as via action mapping or through TryActivate functions), but you may be okay with this if the ability is meant to be purely passive and response-based.

If you want an ability that does need both gameplay event structs when called via GameplayEvent while still being eligible for manual activations with action mappings/TryActivate, you're best off just splitting active and response-based ability activations into separate abilities that are usually delivered in one bundle.

### Targeting

Way back in the Tasks section we looked at an example task called Wait for Target Data. This task is particularly significant within the AbilitySystem because not only does it provide a system for visualising the targeting of an ability, it provides a framework for the player to send data client->server.

When using this node, the first thing to note is that it is likely best to place before CommitAbility. This is because you can give the player the option to see what their ability is going to do before they choose to activate it. There's a couple of options for Confirmation Type, but the main two are Instant and User Confirmed. These two options are a simple way to swap between quick-casting (Instant), and requiring additional input to confirm and continue the ability. The class option needs to be a child of AGameplayAbilityTargetActor. We'll get to that shortly. We also have some options for a reticle, which I don't use so we won't be covering it, and a filter option. The filter will only really be relevant if you're going to be targeting actors, as opposed to targeting a location or some other thing. A good example might be an AoE spell that affects all targets within a circle - using the filter we can remove the caster from the list of targets, so that we neither highlight them during targeting nor apply effects to them later in the ability.

![Wait Target Data](https://github.com/NickGlenn/Unreal-Engine-4-Community-Guide/tree/58f38c224a525dc8480d25ca361411d9d3e3ff4c/.gitbook/assets/waittargetdata.png)

If you've selected User Confirmed for the Confirmation Type. You'll need to either call `UAbilitySystemComponent::TargetConfirm()` or have Confirm as part of you input binds discussed earlier. You can also call `UAbilitySystemComponent::TargetCancel()` or use Cancel from the input binding if you want to give the player the option to see where they're aiming and then stop the ability from doing anything if they change their mind. This is particularly handy if creating abilities that build or place things in the world. If you're doing user confirmed remember to link the cancelled pin to EndAbility to clean things up!

The data pin on the right of the Task Node will be valid on both the client and the server, and the Valid Data delegate will fire on both. At the back end, this is done in an interesting way since while the task has spawned an Actor (the Targeting Actor), this actor is NOT replicated. So the RPC to send the client data actually goes via the AbilitySystemComponent, which is part of the reason why Targeting Actors are a little peculiar to set up.

#### Target Actors

To create a new Targeting Actor, create a new child inheriting from AGameplayAbilityTargetActor. The two main methods you need to implement are `virtual void StartTargeting(UGameplayAbility* Ability) override` and `virtual void ConfirmTargetingAndContinue() override`.

In StartTargeting, you have the Ability Instance, so sometimes you'll pull in some information about the Ability you're visualising and targeting for from there. An example would be if you have a generic ability for building walls, you might have the type of wall available in the Ability so that the Targeting Actor can find out what mesh it should display. This is also your opportunity to get a ptr to the Avatar that activated the ability, so if anything to do with targeting is dependent on what tags or attributes the Avatar has (maybe the character's AoE size increases based on an attribute) then now is the time to grab that.

ConfirmTargetingAndContinue is where things get weird, but if we distill it down to its most simple, what we want to do is fire the TargetDataReadyDelegate with a payload containing our target data. So if we wanted to send down two transforms containing a source location and a destination, it's going to look something like this:

```cpp
FGameplayAbilityTargetData_LocationInfo *ReturnData = new FGameplayAbilityTargetData_LocationInfo();
ReturnData->SourceLocation.LocationType = EGameplayAbilityTargetingLocationType::LiteralTransform;
ReturnData- >SourceLocation.LiteralTransform = FTransform(SourceLocation);
ReturnData- >TargetLocation.LocationType = EGameplayAbilityTargetingLocationType::LiteralTransform;
ReturnData- >TargetLocation.LiteralTransform = FTransform((TargetLocation - SourceLocation).ToOrientationQuat(), TargetLocation);
FGameplayAbilityTargetDataHandle Handle(ReturnData);
TargetDataReadyDelegate.Broadcast(Handle);
```

The key struct is `FGameplayAbilityTargetData`, which `FGameplayAbilityTargetData_LocationInfo` and other variants inherit from. So if you want to send a location or two, use `FGameplayAbilityTargetData_LocationInfo`, if you want to send some actors, use `FGameplayAbilityTargetData_ActorArray`, if you want to send a hitresult, use `FGameplayAbilityTargetData_SingleTargetHit`. These cover most common use cases, but let's assume you're a special snowflake and you want to send some other piece of data that isn't covered. Remember, this is your method for pushing data client->server for ability activation, and as such it can be tampered with by cheaters, so be really careful with what you send and what you do with it. I (/u/woppin) use this for sending a float that states how long the button has been held for. The server also has this value, but it's not exact, so it's checked against the player's ping and the value the player sent to make sure it's reasonable. You have been warned.

OK, so you still want to send some more info client->server and you understand the risks. In this example we're going to send a source and destination location, plus a float and an int. In the actual project, this is used to let the player click and drag to draw a line (source and destination) that becomes a wall, with the time the button is held (float) increasing the strength of the wall. First thing to do is to create a struct that inherits from `FGameplayAbilityTargetData`:

```cpp
USTRUCT(BlueprintType)
struct FGameplayAbilityCastingTargetingLocationInfo : public FGameplayAbilityTargetData
{
    GENERATED_USTRUCT_BODY()

    /** Amount of time the ability has been charged */
    UPROPERTY(BlueprintReadWrite, EditAnywhere, Category = Targeting)
    float ChargeTime;

    /** The ID of the Ability that is performing targeting */
    UPROPERTY()
    uint32 UniqueID;

    /** Generic location data for source */
    UPROPERTY(BlueprintReadWrite, EditAnywhere, Category = Targeting)
    FGameplayAbilityTargetingLocationInfo SourceLocation;

    /** Generic location data for target */
    UPROPERTY(BlueprintReadWrite, EditAnywhere, Category = Targeting)
    FGameplayAbilityTargetingLocationInfo TargetLocation;

    // -------------------------------------
    virtual bool HasOrigin() const override
    {
        return true;
    }

    virtual FTransform GetOrigin() const override
    {
        return SourceLocation.GetTargetingTransform();
    }

    // -------------------------------------
    virtual bool HasEndPoint() const override
    {
        return true;
    }

    virtual FVector GetEndPoint() const override
    {
        return TargetLocation.GetTargetingTransform().GetLocation();
    }

    virtual FTransform GetEndPointTransform() const override
    {
        return TargetLocation.GetTargetingTransform();
    }

    // -------------------------------------
    virtual UScriptStruct* GetScriptStruct() const override
    {
        return FGameplayAbilityCastingTargetingLocationInfo::StaticStruct();
    }

    virtual FString ToString() const override
    {
        return TEXT("FGameplayAbilityCastingTargetingLocationInfo");
    }

    bool NetSerialize(FArchive&amp; Ar, class UPackageMap* Map, bool&amp; bOutSuccess);
};

template<>
struct TStructOpsTypeTraits<FGameplayAbilityCastingTargetingLocationInfo> : public TStructOpsTypeTraitsBase2<FGameplayAbilityCastingTargetingLocationInfo>
{
    enum
    {
        WithNetSerializer = true    // For now this is REQUIRED for FGameplayAbilityTargetDataHandle net serialization to work
    };
};
```

I have no idea what that last part does! In our .cpp we need to add an implementation for NetSerialize to include our new data (a float and an int):

```cpp
bool FGameplayAbilityCastingTargetingLocationInfo::NetSerialize(FArchive& Ar, class UPackageMap* Map, bool& bOutSuccess)
{
    SourceLocation.NetSerialize(Ar, Map, bOutSuccess);
    TargetLocation.NetSerialize(Ar, Map, bOutSuccess);
    Ar << ChargeTime;
    Ar << UniqueID;
    bOutSuccess = true;
    return true;
}
```

Now we update our targeting confirmation to include new data:

```cpp
FGameplayAbilityCastingTargetingLocationInfo *ReturnData = new FGameplayAbilityCastingTargetingLocationInfo();
ReturnData->ChargeTime = CastingCharacter- >GetChargeTime(); // Get the wall strength
ReturnData->UniqueID = OwningAbility- >GetUniqueID(); // Ignore this
FVector SourceLocation = CastingCharacter->GetCastingSourceLocation(); // Get where the character is aiming from
FVector TargetLocation = CastingCharacter->GetCastingTargetLocation(); // Get where the character is aiming to
ClampLocations(SourceLocation, TargetLocation); // Limit the maximum wall length

// Set Location Data
ReturnData->SourceLocation.LocationType = EGameplayAbilityTargetingLocationType::LiteralTransform;
ReturnData->SourceLocation.LiteralTransform = FTransform(SourceLocation);
ReturnData->TargetLocation.LocationType = EGameplayAbilityTargetingLocationType::LiteralTransform;
ReturnData->TargetLocation.LiteralTransform = FTransform((TargetLocation - SourceLocation).ToOrientationQuat(), TargetLocation);
FGameplayAbilityTargetDataHandle Handle(ReturnData);
TargetDataReadyDelegate.Broadcast(Handle);
```

The last remaining pieces worth mentioning are firstly that you can visualise the ability in the actor as well, but how you do that is entirely up to you, and secondly you might want to re-use the targeting actor if you're rapidly re-firing the same ability over and over. Also note that if the ability is instant, the actor will spawn and then immediately be destroyed, so visualisation is a bit pointless. For visualisation generally follow the model of spawning the meshes/particles you need in StartTargeting, and then use tick to update each frame based on changes in player input. This will probably mean storing where you're aiming in the PlayerController or the Character's Tick, storing a ptr to one of those two in StartTargeting, and then Calling out to them during the TargetingActor's Tick. Of course you don't have to use tick if you're not doing analogue targeting (eg. targeting controlled by keys instead of mouse) or if you can handle a lower refresh rate and use a Timer instead.

There's quite a few examples of TargetingActors already in the Plugin, so look at them if in doubt.

## Conclusion

That's it! You now have a somewhat complete overview of the module's core systems, as well as their helper systems that allow better interaction between each of them.

Questions, and typo-searching would be appreciated. As would be complementing sections of this guide with knowledge and discoveries of your own should you garner enough experience to contribute, as while I feel like I have a rough overview of the module down, a lot of the fine lines of this system are still lost on me.

Once again, this guide is taken from [a post on the forums](https://forums.unrealengine.com/showthread.php?137352-GameplayAbilities-and-you) by [KZJ](https://forums.unrealengine.com/member.php?267563-KZJ), and was originally adapted for the Unreal Engine wiki by Jay2645.

## Common Issues

#### Cues not visible in packaged game

By default, only referenced assets are included in packaged builds, and if you've set up your GameplayCues to be triggered by tags this won't be enough. GameplayCues usually inherit from one of two base classes, so they can be added to the Asset Manager like so:

![Cue Packaging](https://github.com/NickGlenn/Unreal-Engine-4-Community-Guide/tree/58f38c224a525dc8480d25ca361411d9d3e3ff4c/.gitbook/assets/cuepackaging.png)


# DevOps


# Linking DLLs

This wiki article was written by Original Author ZkarmaKun (talk); Updated & Improved by F3NR1S (talk), XenoEgger, Darkgaze; Converted by jfaw

## Overview

This tutorial explains how to link / bind your own [DLL](https://en.wikipedia.org/wiki/Dynamic-link_library) to Unreal Engine 4 and how to use your DLL's methods for visual scripting in a [Blueprint Function Library](https://docs.unrealengine.com/latest/INT/Programming/BlueprintFunctionLibraries/).

## Creating a C++ DLL

This article originally centered on binding the DLL but here is also a brief explanation on how to build DLLs in different [IDEs](https://en.wikipedia.org/wiki/Integrated_development_environment).

### Visual Studio Community 2015

* Create a new project: *menu bar -> File -> New -> Project...*
  1. In the New Project window on the left select *Installed -> Templates -> Visual C++ -> Win32.*
  2. Select *Win32 Project* in the middle.
  3. Name: the project *CreateAndLinkDLLTut* and the Solution name: *CreateAndLinkDLLTutSol*.
  4. Click *OK*.&#x20;
* In the next window *Win32 Application Wizard - CreateAndLinkDLLTut* click *Next*.
  1. In the **Application Settings** select
     * *Application type: -> DLL*
     * *Additional options: -> Empty project*
  2. Click *Finish*.&#x20;
* On the left side of Visual Studio in the Solution Explorer make sure that CreateAndLinkDLLTut is selected.
  1. Click *main menu -> Project -> Add Class...*
  2. In the *Add Class* window select *Installed -> Visual C++ -> C++ ->* on the left side and *C++ Class* in the middle then click *Add*.
  3. In the *Generic C++ Class Wizard* window fill in *CreateAndLinkDLLfile* into the *Class name: input* field. Click *Finish*.
* On the left side in the *Solution Explorer* select the file *CreateAndLinkDLLfile.h* and copy & paste the following code. Replace all automatically generated code.

```cpp
#pragma once  

#define DLL_EXPORT __declspec(dllexport)    //shortens __declspec(dllexport) to DLL_EXPORT

#ifdef __cplusplus        //if C++ is used convert it to C to prevent C++'s name mangling of method names
extern "C"
{
#endif

    bool DLL_EXPORT getInvertedBool(bool boolState);
    int DLL_EXPORT getIntPlusPlus(int lastInt);
    float DLL_EXPORT getCircleArea(float radius);
    char DLL_EXPORT *getCharArray(char* parameterText);
    float DLL_EXPORT *getVector4( float x, float y, float z, float w);

#ifdef __cplusplus
}
#endif
```

* Then select the file *CreateAndLinkDLLfile.cpp* and copy & paste the following code. Replace all automatically generated code.

```cpp
#pragma once

#include "string.h"
#include "CreateAndLinkDLLFile.h"


//Exported method that invertes a given boolean.
bool getInvertedBool(bool boolState)
{
    return bool(!boolState);
}

//Exported method that iterates a given int value.
int getIntPlusPlus(int lastInt)
{
    return int(++lastInt);
}

//Exported method that calculates the are of a circle by a given radius.
float getCircleArea(float radius)
{
    return float(3.1416f * (radius * radius));
}

//Exported method that adds a parameter text to an additional text and returns them combined.
char *getCharArray(char* parameterText)
{
    char* additionalText = " world!";

    if (strlen(parameterText) + strlen(additionalText) + 1 > 256)
    {
        return "Error: Maximum size of the char array is 256 chars.";
    }

    char combinedText[256] = "";

    strcpy_s( combinedText, 256, parameterText);
    strcat_s( combinedText, 256, additionalText);

    return ( char* )combinedText;
}

//Exported method that adds a vector4 to a given vector4 and returns the sum.
float *getVector4( float x, float y, float z, float w )
{
    float* modifiedVector4 = new float[4];

    modifiedVector4[0] = x + 1.0F;
    modifiedVector4[1] = y + 2.0F;
    modifiedVector4[2] = z + 3.0F;
    modifiedVector4[3] = w + 4.0F;

    return ( float* )modifiedVector4;
}
```

* Save with *menu bar -> File -> Save All*.
* Set the proper build options for your 64-bit DLL: In the menu bar select **Release** as *Solution Configuration* and **x64** as *Solution Platform*. ( If you use a 32-bit Windows system please select **x86** instead of x64. )
* Build the DLL with *menu bar -> Build -> Build CreateAndLinkDLLTut*. The Output at the bottom should show a message like *========== Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped ==========*.
* The 64-bit DLL was created in the folder *.../CreateAndLinkDLLTutSol/x64/Release/* and is called *CreateAndLinkDLLTut.dll*. ( The 32-bit DLL was created in the folder *.../CreateAndLinkDLLTutSol/Release/* and is called *CreateAndLinkDLLTut.dll*. [You won't be able to bind the DLL if the platforms are different.](https://answers.unrealengine.com/questions/30927/does-it-make-a-difference-if-you-load-a-custom-win.html) )

## Unreal Engine Project

* On **Unreal Engine**, create a new project: *New Project -> C++ -> Basic Code*.
* Name the project *CreateAndLinkDLLProj* and create it.
* Open **Windows Explorer**.
  1. Go to the main folder of your created UE4 project.
  2. Add a folder called [Plugins](https://docs.unrealengine.com/latest/INT/Programming/Plugins/index.html#pluginfolders).
  3. In the Plugins folder create an other folder called *MyTutorialDLLs*.
  4. Copy and paste the DLL *CreateAndLinkDLLTut.dll* you have created earlier into the folder *MyTutorialDLLs*.&#x20;
* Add a new C++ class to your project in **Unreal Editor**.
* Choose the *Blueprint Function Library* as the base class.
* Name your blueprint function library *CreateAndLinkDLLTutBFL*.
* If **Visual Studio** does not open it automatically, open it by double clicking *CreateAndLinkDLLTutBFL* in the UE4 content browser.
* Open the *CreateAndLinkDLLTutBFL.h* and *CreateAndLinkDLLTutBFL.cpp* files.
* Select the file *CreateAndLinkDLLTutBFL.h* and copy & paste the following code:

```cpp
#pragma once

#include "Kismet/BlueprintFunctionLibrary.h"
#include "CreateAndLinkDLLTutBFL.generated.h"


UCLASS()
class CREATEANDLINKDLLPROJ_API UCreateAndLinkDLLTutBFL : public UBlueprintFunctionLibrary
{
    GENERATED_BODY()

public:

    UFUNCTION(BlueprintCallable, Category = "My DLL Library")
    static bool importDLL( FString folder, FString name);


    UFUNCTION(BlueprintCallable, Category = "My DLL Library")
    static bool importMethodGetInvertedBool( );

    UFUNCTION(BlueprintCallable, Category = "My DLL Library")
    static bool importMethodGetIntPlusPlus( );

    UFUNCTION(BlueprintCallable, Category = "My DLL Library")
    static bool importMethodGetCircleArea( );

    UFUNCTION(BlueprintCallable, Category = "My DLL Library")
    static bool importMethodGetCharArray( );

    UFUNCTION( BlueprintCallable, Category = "My DLL Library" )
    static bool importMethodGetVector4( );


    UFUNCTION(BlueprintCallable, Category = "My DLL Library")
    static bool getInvertedBoolFromDll(bool boolState);

    UFUNCTION(BlueprintCallable, Category = "My DLL Library")
    static int getIntPlusPlusFromDll(int lastInt);

    UFUNCTION(BlueprintCallable, Category = "My DLL Library")
    static float getCircleAreaFromDll(float radius);

    UFUNCTION(BlueprintCallable, Category = "My DLL Library")
    static FString getCharArrayFromDll(FString parameterText);

    UFUNCTION( BlueprintCallable, Category = "My DLL Library" )
    static FVector4 getVector4FromDll( FVector4 vector4 );


    UFUNCTION(BlueprintCallable, Category = "My DLL Library")
    static void freeDLL();
};
```

* Select the file *CreateAndLinkDLLTutBFL.cpp* and copy & paste the following code:

```cpp
#include "CreateAndLinkDLLProj.h"
#include "CreateAndLinkDLLTutBFL.h"

typedef bool(*_getInvertedBool)(bool boolState); // Declare a method to store the DLL method getInvertedBool.
typedef int(*_getIntPlusPlus)(int lastInt); // Declare a method to store the DLL method getIntPlusPlus.
typedef float(*_getCircleArea)(float radius); // Declare a method to store the DLL method getCircleArea.
typedef char*(*_getCharArray)(char* parameterText); // Declare a method to store the DLL method getCharArray.
typedef float*(*_getVector4)(float x, float y, float z, float w); // Declare a method to store the DLL method getVector4.

_getInvertedBool m_getInvertedBoolFromDll;
_getIntPlusPlus m_getIntPlusPlusFromDll;
_getCircleArea m_getCircleAreaFromDll;
_getCharArray m_getCharArrayFromDll;
_getVector4 m_getVector4FromDll;

void *v_dllHandle;


#pragma region Load DLL

// Method to import a DLL.
bool UCreateAndLinkDLLTutBFL::importDLL(FString folder, FString name)
{
    FString filePath = *FPaths::GamePluginsDir() + folder + "/" + name;

    if (FPaths::FileExists(filePath))
    {
        v_dllHandle = FPlatformProcess::GetDllHandle(*filePath); // Retrieve the DLL.
        if (v_dllHandle != NULL)
        {
            return true;
        }
    }
    return false;    // Return an error.
}
#pragma endregion Load DLL

#pragma region Import Methods

// Imports the method getInvertedBool from the DLL.
bool UCreateAndLinkDLLTutBFL::importMethodGetInvertedBool()
{
    if (v_dllHandle != NULL)
    {
        m_getInvertedBoolFromDll = NULL;
        FString procName = "getInvertedBool";    // Needs to be the exact name of the DLL method.
        m_getInvertedBoolFromDll = (_getInvertedBool)FPlatformProcess::GetDllExport(v_dllHandle, *procName);
        if (m_getInvertedBoolFromDll != NULL)
        {
            return true;
        }
    }
    return false;    // Return an error.
}

// Imports the method getIntPlusPlus from the DLL.
bool UCreateAndLinkDLLTutBFL::importMethodGetIntPlusPlus()
{
    if (v_dllHandle != NULL)
    {
        m_getIntPlusPlusFromDll = NULL;
        FString procName = "getIntPlusPlus";    // Needs to be the exact name of the DLL method.
        m_getIntPlusPlusFromDll = (_getIntPlusPlus)FPlatformProcess::GetDllExport(v_dllHandle, *procName);
        if (m_getIntPlusPlusFromDll != NULL)
        {
            return true;
        }
    }
    return false;    // Return an error.
}

// Imports the method getCircleArea from the DLL.
bool UCreateAndLinkDLLTutBFL::importMethodGetCircleArea()
{
    if (v_dllHandle != NULL)
    {
        m_getCircleAreaFromDll = NULL;
        FString procName = "getCircleArea";    // Needs to be the exact name of the DLL method.
        m_getCircleAreaFromDll = (_getCircleArea)FPlatformProcess::GetDllExport(v_dllHandle, *procName);
        if (m_getCircleAreaFromDll != NULL)
        {
            return true;
        }
    }
    return false;    // Return an error.
}

// Imports the method getCharArray from the DLL.
bool UCreateAndLinkDLLTutBFL::importMethodGetCharArray()
{
    if (v_dllHandle != NULL)
    {
        m_getCharArrayFromDll = NULL;
        FString procName = "getCharArray";    // Needs to be the exact name of the DLL method.
        m_getCharArrayFromDll = (_getCharArray)FPlatformProcess::GetDllExport(v_dllHandle, *procName);
        if (m_getCharArrayFromDll != NULL)
        {
            return true;
        }
    }
    return false;    // Return an error.
}

// Imports the method getVector4 from the DLL.
bool UCreateAndLinkDLLTutBFL::importMethodGetVector4( )
{
    if( v_dllHandle != NULL )
    {
        m_getVector4FromDll = NULL;
        FString procName = "getVector4";    // Needs to be the exact name of the DLL method.
        m_getVector4FromDll = ( _getVector4 ) FPlatformProcess::GetDllExport( v_dllHandle, *procName );
        if( m_getVector4FromDll != NULL )
        {
            return true;
        }
    }
    return false;    // Return an error.
}

#pragma endregion Import Methods

#pragma region Method Calls

// Calls the method getInvertedBoolFromDll that was imported from the DLL.
bool UCreateAndLinkDLLTutBFL::getInvertedBoolFromDll(bool boolState)
{
    if (m_getInvertedBoolFromDll != NULL)
    {
        bool out = bool(m_getInvertedBoolFromDll(boolState)); // Call the DLL method with arguments corresponding to the exact signature and return type of the method.
        return out;
    }
    return boolState;    // Return an error.
}

// Calls the method m_getIntPlusPlusFromDll that was imported from the DLL.
int UCreateAndLinkDLLTutBFL::getIntPlusPlusFromDll(int lastInt)
{
    if (m_getIntPlusPlusFromDll != NULL)
    {
        int out = int(m_getIntPlusPlusFromDll(lastInt)); // Call the DLL method with arguments corresponding to the exact signature and return type of the method.
        return out;
    }
    return -32202;    // Return an error.
}

// Calls the method m_getCircleAreaFromDll that was imported from the DLL.
float UCreateAndLinkDLLTutBFL::getCircleAreaFromDll(float radius)
{
    if (m_getCircleAreaFromDll != NULL)
    {
        float out = float(m_getCircleAreaFromDll(radius)); // Call the DLL method with arguments corresponding to the exact signature and return type of the method.
        return out;
    }
    return -32202.0F;    // Return an error.
}

// Calls the method m_getCharArrayFromDLL that was imported from the DLL.
FString UCreateAndLinkDLLTutBFL::getCharArrayFromDll(FString parameterText)
{
    if (m_getCharArrayFromDll != NULL)
    {
        char* parameterChar = TCHAR_TO_ANSI(*parameterText);

        char* returnChar = m_getCharArrayFromDll(parameterChar);

        return (ANSI_TO_TCHAR(returnChar));
    }
    return "Error: Method getCharArray was probabey not imported yet!";    // Return an error.
}

// Calls the method m_getVector4FromDll that was imported from the DLL.
FVector4 UCreateAndLinkDLLTutBFL::getVector4FromDll( FVector4 vector4 )
{
    if( m_getVector4FromDll != NULL )
    {
        float* vector4Array = m_getVector4FromDll( vector4.X, vector4.Y, vector4.Z, vector4.W );

        return FVector4( vector4Array[0], vector4Array[1], vector4Array[2], vector4Array[3] );
    }
    return FVector4( -32202.0F, -32202.0F, -32202.0F, -32202.0F );    // Return an error.
}
#pragma endregion Method Calls


#pragma region Unload DLL

// If you love something  set it free.
void UCreateAndLinkDLLTutBFL::freeDLL()
{
    if (v_dllHandle != NULL)
    {
        m_getInvertedBoolFromDll = NULL;
        m_getIntPlusPlusFromDll = NULL;
        m_getCircleAreaFromDll = NULL;
        m_getCharArrayFromDll = NULL;
        m_getVector4FromDll = NULL;

        FPlatformProcess::FreeDllHandle(v_dllHandle);
        v_dllHandle = NULL;
    }
}
#pragma endregion Unload DLL
```

* Save with *menu bar -> File -> Save All*.

## Creating the Blueprint

* First hit the Compile button PD CompileButton.PNG of the Unreal Editor to compile the code you've added and saved in Visual Studio before.
* In Unreal Editor add a new Blueprint Class called *BP\_DllTest* and open it. ([How to create a blueprint class](https://docs.unrealengine.com/latest/INT/Engine/Blueprints/UserGuide/Types/ClassBlueprint/Creation/index.html))
* Select the *Event Graph* and add the following nodes construct ( Click it and click it again to download it! ).&#x20;
  * **Important note**: If you don't see the functions in the dropdown, try compiling from Visual Studio and then reopening UE4. If this doesn't work, close UE4, remove Binaries folder and Intermediate folder (but avoid deleting Intermediate/Project Files). You will be prompted to rebuild the project.

![Project Creation](https://930279451-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M3mx7Lszp8LdwKKD7yR%2F-M462J1RJdKu8dvwBJxs%2F-M462LJrNMXkTkd6Ynoa%2Fblueprint-graph1.png?generation=1586035001296251\&alt=media)

* Then compile and save the blueprint and drag & drop it into the level.
* The result should look like this:

![Project Creation](https://930279451-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M3mx7Lszp8LdwKKD7yR%2F-M462J1RJdKu8dvwBJxs%2F-M462LJtYXOAZAmd5Lby%2Fresult1.png?generation=1586035000084745\&alt=media)

## Project Source Code

You can download the final [Visual Studio Solution of the DLL](https://github.com/XenoEgger/CreateAndLinkDLLTutSol) and the [Unreal Engine 4 project](https://github.com/XenoEgger/CreateAndLinkDLLProj) from GitHub. ( You may need to rebuild the DLL and copy it to your UE4 *Plugins* folder. )

## Final Words

* You can use any DLL from C code or C++ or other languages.
* You can use unmanaged or managed (CLR, .Net Framework) code from a project in your solution or external.
* Most issues arise from differences in the signature of the DLL function and the type definition in the Unreal Project.
* Automatic packaging of third party DLL is not yet supported, you will need to package the DLL, the DLL folder and the plugin folder as well, which is not created in a package by default at this time.
* Be mindful of load times of DLL, it may slow down your project.
* Be mindful of processing time of your DLL, your project loses execution control inside the DLL, until it returns, it may be expensive to perform some operations.
* To go further with this tutorial:
  * C++ with proper class, namespace and name mangling.
  * DLL with multithreading and callback example.


# AR & VR

Augmented Reality & Virtual Reality


# Integrating OpenCV into Unreal Engine 4

This article was originally written by Ginku; Converted by jfaw

## Overview

Hello all! This is my first wiki tutorial, I hope it can be of help to someone!

I am making this tutorial in response to a few requests. This will be a detailed, step-by-step guide to linking OpenCV 3.2 to Unreal Engine 4 using the Unreal Build Tool. You can find a general tutorial on linking any static library to Unreal [here](https://github.com/NickGlenn/Unreal-Engine-4-Community-Guide/tree/1c9f59fcc997508eb51f94b2d1e18c3544296406/wiki-archives/ar-vr/Linking_Static_Libraries_Using_The_Build_System/README.md). I recommend reading it in addition to this tutorial, as it is what this tutorial is based on.

This tutorial focuses on the windows OS for simplicity. Note that the same process works for other OS, but you might need to build OpenCV from source.

### Why OpenCV?

OpenCV is a powerful open-source computer vision library, and once included into any unreal engine 4 project it will allow for the use of the engine in many non-traditional ways. Including OpenCV in a project as a dependency will allow developers to create state-of-the-art environments with either augmented reality components, virtual reality environments that resemble the user’s surroundings, or any mixture of the two. In this tutorial I will show you how to quickly and painlessly include OpenCV in any unreal engine 4 project with the Windows OS, and then I will guide you through displaying a webcam in a level.

### Using the Plugin

I have created a plugin that does all the OpenCV library linking, which can be found on its github. Installation instructions are inside the README file. With this plugin, you can skip to the Moving to Blueprints section of this tutorial. If you do so, be sure to enable the Computer Vision > OpenCV plugin inside the editor's Edit > Plugins menu.

Note: after installation, be sure to regenerate project files. For visual studios, right click your project (.uasset) file and select 'generate visual studio project files' after deleting your previous visual studios file.

## Linking OpenCV in Visual Studios

Before you continue, make sure you are starting from a code project, or have added code to your project with the editor!

### Copying the OpenCV Files

In order to begin, all of OpenCV’s include and library files will need to be added to your project’s `/ThirdParty` directory. To begin, install **OpenCV 3.2** or locate your installation of OpenCV 3.2 and do the following:

* Inside the OpenCV install directory you will find the `/build/include` directory. Copy all of the contents of this directory into the `[ProjectRootDirectory]/ThirdParty/OpenCV/Includes` directory.
* Next, copy the *opencv\_world320.dll* and *opencv\_ffmpeg320\_64.dll* files in the `/build/x64/vc14/bin` folder and the 'opencv\_world320.lib', files in the `/build/x64/vc14/lib` folder to the `[ProjectRootDirectory]/ThirdParty/OpenCV/Libraries/Win64/` directory.

*Note:* This process is similar for any version of OpenCV or any third party library. You only need the runtime libraries (not the debug ones with a 'd' appended, such as *opencv\_world320d.dll* unless you need the debug versions).

### Adding OpenCV Dependencies

Locate and open your projects module rules file, which should be in your projects `Source/[Project Name]` directory. (It will be in the format of *ProjectName.Build.cs*) In this file, we will add the necessary code so that the unreal build tool will include all of the necessary dependencies during build time.

First, be sure to add the following include at the top of the file:

```csharp
using System.IO;
```

This lets you use the Path helper class, which is very useful for assembling directory paths!

Inside your ModuleRules class and before the constructor, add the following getter:

```csharp
private string ThirdPartyPath
{ 
    get { return Path.GetFullPath(Path.Combine(ModuleDirectory, "../../ThirdParty/")); } 
}
```

This is a helpful little function for retrieving the `/ThirdParty/` path, and can be very convenient when including more than one third party dependency to a project. Now, add the following function after the constructor:

```csharp
public bool LoadOpenCV(TargetInfo Target)
{
    // Start OpenCV linking here!
    bool isLibrarySupported = false;

    // Create OpenCV Path 
    string OpenCVPath = Path.Combine(ThirdPartyPath, "OpenCV");

    // Get Library Path 
    string LibPath = "";
    bool isdebug = Target.Configuration == UnrealTargetConfiguration.Debug && BuildConfiguration.bDebugBuildsActuallyUseDebugCRT;
    if (Target.Platform == UnrealTargetPlatform.Win64)
    {
        LibPath = Path.Combine(OpenCVPath, "Libraries", "Win64");
        isLibrarySupported = true;
    }
    else
    {
        string Err = string.Format("{0} dedicated server is made to depend on {1}. We want to avoid this, please correct module dependencies.", Target.Platform.ToString(), this.ToString()); System.Console.WriteLine(Err);
    }

    if (isLibrarySupported)
    {
        //Add Include path 
        PublicIncludePaths.AddRange(new string[] { Path.Combine(OpenCVPath, "Includes") });

        // Add Library Path 
        PublicLibraryPaths.Add(LibPath);

        //Add Static Libraries
        PublicAdditionalLibraries.Add("opencv_world320.lib");

        //Add Dynamic Libraries
        PublicDelayLoadDLLs.Add("opencv_world320.dll");
        PublicDelayLoadDLLs.Add("opencv_ffmpeg320_64.dll");
    }

    Definitions.Add(string.Format("WITH_OPENCV_BINDING={0}", isLibrarySupported ? 1 : 0));

    return isLibrarySupported;
}
```

This function includes all of the required includes and libraries for OpenCV. Now, simply call this function inside your project constructor after the standard public modules:

```csharp
PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore", "RHI", "RenderCore", "ShaderCore" });

LoadOpenCV(Target);
```

Be sure to add the **InputCore**, **RHI**, and **RenderCore** engine modules to the *public* dependency list, we will use these later to create a dynamic texture from the camera feed. The *PrivateIncludePaths* will allow you to include the OpenCV header files without full paths.

Now, your project should successfully compile with OpenCV included within the engine build! However, there is one more thing that needs to be included before you can launch an instance of your project’s editor.

### Copying the DLL's to the Build

Before your project will run with any OpenCV code, you will first need to add all of the dynamically linked library (*.dll*) files that you use to your editor’s bin folder. Your editor will typically be a 64-bit application, so copy all of the *.dll* files (*opencv\_world320.dll* and *opencv\_ffmpeg320\_64.dll*) from the OpenCV’s 64 bit bin folder (full directory shown above) and paste them inside the `[ProjectRootDirectory]/Binaries/Win64` directory.

Note: These DLL's should also be included with any distributions of the project (such as when packaging your game/project), by including them in the same directory as the project's executable (`MY_PROJECT.exe`).

### Fixing Library Collisions

There is a collision between the OpenCV3 library and UE4. To fix this, **comment out lines \~51 to \~55 and line \~852** of the *utility.hpp* header file in the `'[ProjectRootDirectory]\ThirdParty\OpenCV\Includes\opencv2\core` directory.

```cpp
// NOTE: The OpenCV 'check' function has been commented out, as it conflicts with UE4 check - see line ~852
//#if defined(check)
//#  warning Detected Apple 'check' macro definition, it can cause build conflicts. Please, include this header before any Apple headers.
//#endif

...

//bool check() const;
```

## Adding a WebcamReader Class

You are now ready to launch an instance of your editor and start using OpenCV! Right click the project name in your solution explorer, and select *Debug > Start new instance*. If you get an error about the os being unable to load your dll, check out the discussion page. Once the editor loads, select *File > New C++ Class…* and select the `Actor` parent class. Press Next, name the actor `WebcamReader` and press *Create Class*. Once Unreal has finished adding the new actor, the new header and source files will be opened inside Visual Studios.

Add the following code to each of them:

#### Header

```cpp
// A simple webcam reader using the OpenCV library
// Author: The UE4 community

#pragma once

#include "opencv2/core.hpp"
#include "opencv2/highgui.hpp"    
#include "opencv2/imgproc.hpp"
#include "opencv2/videoio.hpp"
#include "GameFramework/Actor.h"
#include "Runtime/Engine/Classes/Engine/Texture2D.h"
#include "WebcamReader.generated.h"

UCLASS()
class YOURPROJECT_API AWebcamReader : public AActor
{
    GENERATED_BODY()

public:    
    // Sets default values for this actor's properties
    AWebcamReader();

    // Called when the game starts or when spawned
    virtual void BeginPlay() override;

    // Called every frame
    virtual void Tick( float DeltaSeconds ) override;

    // The device ID opened by the Video Stream
    UPROPERTY(BlueprintReadWrite, EditAnywhere, Category = Webcam)
    int32 CameraID;

    // If the webcam images should be resized every frame
    UPROPERTY(BlueprintReadWrite, EditAnywhere, Category = Webcam)
    bool ShouldResize;

    // The targeted resize width and height (width, height)
    UPROPERTY(BlueprintReadWrite, EditAnywhere, Category = Webcam)
    FVector2D ResizeDeminsions;

    // The rate at which the color data array and video texture is updated (in frames per second)
    UPROPERTY(BlueprintReadWrite, EditAnywhere, Category = Webcam)
    float RefreshRate;

    // The refresh timer
    UPROPERTY(BlueprintReadWrite, Category = Webcam)
    float RefreshTimer;

    // Blueprint Event called every time the video frame is updated
    UFUNCTION(BlueprintImplementableEvent, Category = Webcam)
    void OnNextVideoFrame();

    // OpenCV fields
    cv::Mat frame;
    cv::VideoCapture stream;
    cv::Size size;

    // OpenCV prototypes
    void UpdateFrame();
    void DoProcessing();
    void UpdateTexture();

    // If the stream has succesfully opened yet
    UPROPERTY(BlueprintReadOnly, Category = Webcam)
    bool isStreamOpen;

    // The videos width and height (width, height)
    UPROPERTY(BlueprintReadWrite, Category = Webcam)
    FVector2D VideoSize;

    // The current video frame's corresponding texture
    UPROPERTY(BlueprintReadOnly, Category = Webcam)
    UTexture2D* VideoTexture;

    // The current data array
    UPROPERTY(BlueprintReadOnly, Category = Webcam)
    TArray<FColor> Data;

protected:

    // Use this function to update the texture rects you want to change:
    // NOTE: There is a method called UpdateTextureRegions in UTexture2D but it is compiled WITH_EDITOR and is not marked as ENGINE_API so it cannot be linked
    // from plugins.
    // FROM: https://wiki.unrealengine.com/Dynamic_Textures
    void UpdateTextureRegions(UTexture2D* Texture, int32 MipIndex, uint32 NumRegions, FUpdateTextureRegion2D* Regions, uint32 SrcPitch, uint32 SrcBpp, uint8* SrcData, bool bFreeData);

    // Pointer to update texture region 2D struct
    FUpdateTextureRegion2D* VideoUpdateTextureRegion;
};
```

#### Source

```cpp
// A simple webcam reader using the OpenCV library
// Author: The UE4 community

#include "YOURPROJECT.h"
#include "WebcamReader.h"

// Sets default values
AWebcamReader::AWebcamReader()
{
     // Set this actor to call Tick() every frame.  You can turn this off to improve performance if you don't need it.
    PrimaryActorTick.bCanEverTick = true;

    // Initialize OpenCV and webcam properties
    CameraID = 0;
    RefreshRate = 15;
    isStreamOpen = false;
    VideoSize = FVector2D(0, 0);
    ShouldResize = false;
    ResizeDeminsions = FVector2D(320, 240);
    RefreshTimer = 0.0f;
    stream = cv::VideoCapture();
    frame = cv::Mat();
}

// Called when the game starts or when spawned
void AWebcamReader::BeginPlay()
{
    Super::BeginPlay();

    // Open the stream
    stream.open(CameraID);
    if (stream.isOpened())
    {
        // Initialize stream
        isStreamOpen = true;
        UpdateFrame();
        VideoSize = FVector2D(frame.cols, frame.rows);
        size = cv::Size(ResizeDeminsions.X, ResizeDeminsions.Y);
        VideoTexture = UTexture2D::CreateTransient(VideoSize.X, VideoSize.Y);
        VideoTexture->UpdateResource();
        VideoUpdateTextureRegion = new FUpdateTextureRegion2D(0, 0, 0, 0, VideoSize.X, VideoSize.Y);

        // Initialize data array
        Data.Init(FColor(0, 0, 0, 255), VideoSize.X * VideoSize.Y);

        // Do first frame
        DoProcessing();
        UpdateTexture();
        OnNextVideoFrame();
    }

}

// Called every frame
void AWebcamReader::Tick( float DeltaTime )
{
    Super::Tick( DeltaTime );

    RefreshTimer += DeltaTime;
    if (isStreamOpen && RefreshTimer >= 1.0f / RefreshRate)
    {
        RefreshTimer -= 1.0f / RefreshRate;
        UpdateFrame();
        DoProcessing();
        UpdateTexture();
        OnNextVideoFrame();
    }
}

void AWebcamReader::UpdateFrame()
{
    if (stream.isOpened())
    {
        stream.read(frame);
        if (ShouldResize)
        {
            cv::resize(frame, frame, size);
        }
    }
    else {
        isStreamOpen = false;
    }
}

void AWebcamReader::DoProcessing()
{
    // TODO: Do any processing here!
}

void AWebcamReader::UpdateTexture()
{
    if (isStreamOpen && frame.data)
    {
        // Copy Mat data to Data array
        for (int y = 0; y < VideoSize.Y; y++)
        {
            for (int x = 0; x < VideoSize.X; x++)
            {
                int i = x + (y * VideoSize.X);
                Data[i].B = frame.data[i * 3 + 0];
                Data[i].G = frame.data[i * 3 + 1];
                Data[i].R = frame.data[i * 3 + 2];
            }
        }

        // Update texture 2D
        UpdateTextureRegions(VideoTexture, (int32)0, (uint32)1, VideoUpdateTextureRegion, (uint32)(4 * VideoSize.X), (uint32)4, (uint8*)Data.GetData(), false);
    }
}

void AWebcamReader::UpdateTextureRegions(UTexture2D* Texture, int32 MipIndex, uint32 NumRegions, FUpdateTextureRegion2D* Regions, uint32 SrcPitch, uint32 SrcBpp, uint8* SrcData, bool bFreeData)
{
    if (Texture->Resource)
    {
        struct FUpdateTextureRegionsData
        {
            FTexture2DResource* Texture2DResource;
            int32 MipIndex;
            uint32 NumRegions;
            FUpdateTextureRegion2D* Regions;
            uint32 SrcPitch;
            uint32 SrcBpp;
            uint8* SrcData;
        };

        FUpdateTextureRegionsData* RegionData = new FUpdateTextureRegionsData;

        RegionData->Texture2DResource = (FTexture2DResource*)Texture->Resource;
        RegionData->MipIndex = MipIndex;
        RegionData->NumRegions = NumRegions;
        RegionData->Regions = Regions;
        RegionData->SrcPitch = SrcPitch;
        RegionData->SrcBpp = SrcBpp;
        RegionData->SrcData = SrcData;

        ENQUEUE_UNIQUE_RENDER_COMMAND_TWOPARAMETER(
            UpdateTextureRegionsData,
            FUpdateTextureRegionsData*, RegionData, RegionData,
            bool, bFreeData, bFreeData,
            {
            for (uint32 RegionIndex = 0; RegionIndex < RegionData->NumRegions; ++RegionIndex)
            {
                int32 CurrentFirstMip = RegionData->Texture2DResource->GetCurrentFirstMip();
                if (RegionData->MipIndex >= CurrentFirstMip)
                {
                    RHIUpdateTexture2D(
                        RegionData->Texture2DResource->GetTexture2DRHI(),
                        RegionData->MipIndex - CurrentFirstMip,
                        RegionData->Regions[RegionIndex],
                        RegionData->SrcPitch,
                        RegionData->SrcData
                        + RegionData->Regions[RegionIndex].SrcY * RegionData->SrcPitch
                        + RegionData->Regions[RegionIndex].SrcX * RegionData->SrcBpp
                        );
                }
            }
            if (bFreeData)
            {
                FMemory::Free(RegionData->Regions);
                FMemory::Free(RegionData->SrcData);
            }
            delete RegionData;
        });
    }
}
```

Note: you need to change `YOURPROJECT` in the *class definition of the header file* and the project include in the source file with the correct version, which is based on your project's name.

This class is used as a wrapper for a future unreal blueprint class. It allows you to specify the device ID, target resolution and framerate of the camera, as well as providing a dynamic texture and an `FColor` array of the current frame's pixels and a blueprint native event that is called whenever the next webcam frame is available!

## Moving to Blueprints

You can now access your webcam feed in blueprints. From this point forward we will be working in the editor.

### Adding the WebcamBillboard Actor

Now that all the code has been included for accessing your webcams, I will now show you how to use the dynamic texture from the WebcamReader actor in a new WebcamBillboard subclass. This time, the code will be implemented in unreal blueprints! Launch the editor again with *Debug > Start* new instance. In your choice of directory, right click and add a new blueprint class. At the bottom of the new window, expand *All Classes* and search `AWebcamReader` and select it as the parent class. Name the new blueprint `BP_WebcamBillboard` and open it.

Within the viewport, add a cube static mesh component, and name it `Billboard`. This will be the component that the texture is rendered to. At the beginning of the game, we will want to create a dynamic material instance and set it to the billboard mesh. Under *Variables*, click the + button to add a new *Material Instance Dynamic* called `DynamicMaterial`’ Drag the `Billboard` component onto the Event Graph, and create a *getter* node. Drag out from this new getter and create a *Create Dynamic Material Instance* node and connect the white execution wire to the transparent *BeginPlay* event (or create one). This creates an special Unreal material instance that can be altered at runtime. However, we have not created this Unreal material!

Go back to your content browser, right click and create a new material. Call this material `M_Webcam` and open it. Click on the `M_Webcam` node and set the *Shading Mode* to *Unlit*. Hold `T` and left click anywhere in the new graph to create a texture node. You will have to set the default texture to anything (I used `T_Ceramic_Tile_M`). Right click this node and convert it to a parameter. Call this parameter *Texture* and connect its white `Float3` pin to the *Emissive Color* pin on the `M_Webcam` node. Make sure the save the material!

Now, back in the `BP_WebcamBillboard` blueprint, select the `M_Webcam` as the *Source Material* for the *Create Dynamic Material Instance* node, and make sure the *Element Index* is set to `0`. Drag out from the original billboard getter and create a *Set Material* node. Set the *Material* pin to the output of the *Create Dynamic Material Instance* node, and again make sure the *Element Index* is set to `0`. Finally, drag out the *DynamicMaterial* variable we created earlier and create a setter. Connect the output of the *Create Dynamic Material Instance* node to the *DynamicMaterial* input pin to save a reference of this special material for later use.

We have dynamically set the material of our *Billboard* mesh, and now we need to update its texture parameter each time a new frame is received. To do this, right click on the *Event Graph* and create a *OnNextVideoFrame* event. This event is called in the `AWebcamReader` actor whenever a new frame is read. Drag out the *DynamicMaterial* variable and create a getter underneath the new event. Drag out from the getter and create a *Set Texture Parameter Value* node. Set the *Parameter Name* to *Texture* (the name of the texture parameter in the `M_Webcam` material). Right click on the *Event Graph* and type *VideoTexture* to retrieve a reference to the webcam texture provided by the `AWebcamReader` parent class. Connect the output pin of this *VideoTexture* reference to the *Value* pin of the *Set Texture Parameter Value* node. With that, the `BP_WebcamBillboard` is ready for use!

Drag the `BP_WebcamBillboard` blueprint from the content browser into your level. Orientate and position it however you like, and scale it to a similar scale of your images resolution (about `6.4`, `4.8`, and `0.5` for my webcam). Now, set the Webcam properties in the detail panel. (I used a *Camera ID* of `0`, *Should Resize* to `false`, and *Refresh Rate* of `2.0`) Your *Camera ID* will determine the camera that renders, it should be `0` unless you have more than one webcam. In the case of a laptop, `0` will probably be the integrated laptop, and `1+` will be any additional webcams. You can now press play to see the results!

![Project Creation](https://930279451-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M3mx7Lszp8LdwKKD7yR%2F-M462J1RJdKu8dvwBJxs%2F-M462KI_tlzYuo42EWPr%2Fadding-the-webcam-to-a-level.png?generation=1586034999114250\&alt=media)

You can hold alt and move the object to duplicate it. Change its Camera ID to render a second webcam!

![Project Creation](https://930279451-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M3mx7Lszp8LdwKKD7yR%2F-M462J1RJdKu8dvwBJxs%2F-M462KIbhFQHV753Qkzw%2Fadding-the-webcam-to-a-level2.png?generation=1586034998236324\&alt=media)

Good luck with your OpenCV / UE4 Projects! :)

## Final Notes

For packaged versions of your OpenCV projects, be sure that the executable has access to the dll's. For a windows build, this can be done by coppying the *opencv\_world320.dll* and *opencv\_ffmpeg320\_64.dll* into the `WindowsNoEditor/YOURPROJECT` directory. (There are 2 executables for windows builds, but the one in the `YOURPROJECT` directory is the one that needs access to the dll's, regardless of which one you use to launch your project!)

UE4 and the C++ standard library do not play well together. This can cause annoying crashes, such as with the `cv::findContours` function (often during the `std::vector` destructors). Members of the community have gotten around this by wrapping `findContour` calls in a separate library, and including that in their UE4 projects with steps similar to the ones to include the OpenCV library in this tutorial.

The webcam reader shown in this tutorial is designed to be simple and easy to follow. However, it isn't very efficient, as all of the OpenCV reading code and UE4 dynamic texture code occurs on the game thread, potentially per-tick with high refresh rates! I would recommend separating these parts into another thread to increase performance. Rama's tutorial on multi-threading is a good start if you are unfamiliar with UE4 threads.

If any of these points are confusing, feel free to say so on my talk page and when I get the chance I will add an in-depth section to this tutorial! :)

-Ginku


