UI Button Focus timing not as expected on panel-activation

When I click on a button in my UI a dialog pops up (handled via visibility) and I want to set the focus to a button of that dialog. This is what the desired outcome looks like (using a workaround):

menu_gif

As you can see, I click on the new-game-button. Then the new-game-dialog becomes visible and the focus is set to the yes-button which is part of the new-game-dialog.

The issue seems to be the timing. In my script, I set the visibility of the pop-up dialog to visible and after that I set the focus to the desired button which does not work. The script basically goes like this:
NewGameDialog.style.visibility = Visibility.Visible;
YesBtn.Focus();

I made it work by using a coroutine executing the very next frame via yield return null. To be more precise: setting the visibility happens in the frame the new-game-button was clicked and setting the focus to the yes-button happens the next frame.

While this workaround is not the worst one I ever came up with (not even close), I feel like I am missing something here and it seems like a common use case to me. It’s the first time I am using the UI toolkit so maybe it’s something obvious and I am forcing this behavior in the wrong way. Any advice on how to achieve this without using delayed calls and coroutines?

Hello! This is because while the parent’s visibility has been set to true, it’s only after a frame that we recompute the children’s visibility to true, so when you try to Focus in the same frame, it will check if the child is visible first (it is not yet) before focusing it.

A workaround could be to set the child’s visibility to true as well.

thanks, that was exactly the kind of advice I was looking for :slight_smile:

So glad it was helpful, reach out for any other questions!