RealDocs

TOptional

struct Core Since 4.14
#include "Misc/Optional.h"

Description

A value container that may or may not hold a value of type T, analogous to std::optional. Avoids magic sentinel values (like -1 or nullptr) to express 'no value'.

Signature

template<typename OptionalType> class TOptional

Caveats & Gotchas

  • Calling GetValue() on an unset TOptional asserts in debug builds. Always check IsSet() first.
  • TOptional cannot be used as a UPROPERTY — it's a pure C++ type.
  • Unlike pointer nullability, TOptional has value semantics — it copies the contained object, not a pointer.

Example

Return an optional hit result C++
TOptional<FHitResult> TraceLine(FVector Start, FVector End)
{
    FHitResult Hit;
    if (GetWorld()->LineTraceSingleByChannel(Hit, Start, End, ECC_Visibility))
    {
        return Hit;  // has a value
    }
    return {};  // empty optional
}

TOptional<FHitResult> Result = TraceLine(A, B);
if (Result.IsSet())
{
    UE_LOG(LogTemp, Log, TEXT("Hit: %s"), *Result.GetValue().GetActor()->GetName());
}

Version History

Introduced in: 4.14

Version Status Notes
5.6 stable

Feedback

Was this helpful?

Suggest an edit

Select a field above to begin editing.