How to get the currently focused widget in Unreal Engine

In Unreal Engine, you can determine the currently focused widget in both Slate and UMG UI systems. Slate To get the currently focused Slate widget, you can use the following code snippet: // Instead of 0, you can pass the user index if you have multiple users TSharedPtr<SWidget> FocusedSlateWidget = FSlateApplication::Get().GetUserFocusedWidget(0); UMG Getting the currently focused UMG widget is a bit more involved, since there is no direct function to get it or the place where it is stored....

March 23, 2024 · 1 min · Georgy Treshchev

How to execute code on scope exit in Unreal Engine

If you want to execute some code when the scope is exited, you can use the following handy ON_SCOPE_EXIT macro, like this: int32 AnyFunction() { ON_SCOPE_EXIT { // This code will be executed when the scope is exited (after the return statement) }; // Do smth // Just return 100 for example return 100; }

March 2, 2024 · 1 min · Georgy Treshchev

How to save and restore any value with RAII approach in Unreal Engine

Imagine you’re in a situation where you need to save and restore a value. For instance, let’s say you have a UMG widget that you want to hide temporarily, do some stuff, and then bring back its previous visibility state, all within a single function. The most straightforward approach might be to store the value in a temporary variable, modify it, and then revert it back, like this: ESlateVisibility VisibilityState; const ESlateVisibility PreviousVisibility = VisibilityState; VisibilityState = ESlateVisibility::Hidden; // Do smth....

February 25, 2024 · 2 min · Georgy Treshchev

How to cast Slate widgets in Unreal Engine

This brief article addresses the question of how to cast one Slate widget to another in Unreal Engine. Imagine you have an SWidget widget wrapped in a shared pointer like this: TSharedPtr<SWidget> MyWidgetPtr; If you want to cast it, for example, to an SSpacer, your code might look like this: TSharedPtr<SSpacer> MySpacerPtr = StaticCastSharedPtr<SSpacer>(MyWidgetPtr); It’s important to keep in mind that you should verify whether the shared pointer is valid before using it....

October 21, 2023 · 1 min · Georgy Treshchev

How to set a timer for the next tick in Unreal Engine

In Unreal Engine, it is possible to set a delay for the function to execute after a single tick, which is sometimes useful when working with UMG/Slate side of things where the widget properties are only available after a complete rebuild, such as obtaining the desired size of the widget’s geometry, which is often not accessible right after initializing or constructing the widget. In such cases, you may want to implement a delay, as described in this article , but sometimes even a single tick delay is sufficient and can enhance the overall user experience, preventing visual hitches and abrupt interactions....

September 15, 2023 · 2 min · Georgy Treshchev