How to destroy UMG widget?

I will say there is definitely a use case for destroying widgets, for example, if a Widget is designed to be created with specific info at construct time and that info will never be re-used (and storing the reference and re-running the initialization is inconvenient) or if I know that a Widget will never be seen again then there is a case from a design perspective where I would want to destroy a Widget.

This code in C++ works for me, have tested and it seems like the Widget will be removed from memory entirely:

.h


UFUNCTION(BlueprintCallable, Category = "Optimization", meta=(DefaultToSelf=Object))
static void DestroyObject(UObject* Object);

.cpp



void UYourFunctionLibrary::DestroyObject(UObject* Object) {
    if (Object)
    {
        Object->ConditionalBeginDestroy();
    }
}

6 Likes