UWidget::IsHovered causes a crash

We have a custom UWidget class that represents an item in a menu. There are two places where we call IsHovered on that class and they both crash seemingly randomly.

In the UUserWidget subclass that contains the menu items we iterate over them to see which one is selected using this code:

UMenuItem* NewSelection = nullptr;
for (UMenuItem* MenuItem : Children)
{
	if (MenuItem->IsHovered())
	{
		NewSelection = MenuItem;
		break;
	}
}

Randomly it crashes on the MenuItem->IsHovered() line with an error that says MenuItem is nullptr but when it breaks we can inspect it and it’s not a nullptr and everything in the callstack looks good.

The other place that it crashes is in the UMenuItem class itself. In the tick method we just have some code that checks whether it’s hovered and updates the highlight state of the widget.

Hovered = IsHovered();
UpdateHighlight();

When the crash happens here it says this-> is nullptr but again we can inspect when it breaks and see that this is not the case. We can even step up the callstack and verify that the list that’s holding the menu items looks good.

Has anyone seen a crash like this before?

…. you may check if your MenuItem is not a null value. Mostly sudden crashes caused by access null objects, in your case, it may try to execute ->IsHovered() and it end up with null->IsHovered() and then , crashed. …

try:

if (MenuItem != nullptr) {
   if (MenuItem->IsHovered())
     {
         NewSelection = MenuItem;
         break;
     }
}