ryanjon2040
4 supporters
Unreal Tip #106

Unreal Tip #106

Feb 20, 2021

In UE4, there is templated type called TOptional which is a really useful class. It can be used to check if a certain value is set or not and continue game logic based on the result.

Consider the below code. Let's imagine, in this example we expect bHasWeaponExtrasto be true if the weapon has any attachment, false if no attachments are installed. But what to do if weapon doesn't support any attachments at all?

Without TOptional:

In Header:
bool bHasWeaponExtras;

In Source:// Both true/false can be valid in this context so what will we do?
if (bHasWeaponExtras)
{
// Need an additional check where this bool is not at all set.
// Similar to Nullable<bool> in C#.
}

With TOptional:

In Header:
TOptional<bool> bHasWeaponExtras;

In Source:
// If the value is not set (i.e not true and not false), notify player that this weapon doesn't support any attachments at all.
if (bHasWeaponExtras.IsSet())
{
if (bHasWeaponExtras.GetValue())
{
// Do your thingy.
}
}

Enjoy this post?

Buy ryanjon2040 a coffee

More from ryanjon2040