Select/highlight button from code?

* Edit: I solved this. Solution is in the reply *

Greetings,

I have a settings screen in my game where I allow the user to select what type of mobile control they want to use:

When clicking a button (it’s a TextMeshPro button) it displays using it’s Selected Color:
7740069--972879--upload_2021-12-15_18-45-2.png

I am saving the selected setting and loading it at runtime so I would like the button for the currently selected setting to be “selected” (i.e. display it’s selected color) when the settings screen is loaded.

I see in the inspector debug view a hasSelection property which gets checked when it’s selected:
7740069--972882--upload_2021-12-15_18-45-54.png

I have not found a way to set that via code. I’ve tried calling .Select() on the button component itself. I’ve also tried EventSystem.current.SetSelectedGameObject() on the button’s .gameObject.

Neither of those approaches worked for me:
7740069--972885--upload_2021-12-15_18-48-51.png

My googlefoo has failed me so far.

I’m sure I’m overlooking something obvious and would appreciate someone pointing me in the right direction.

Thanks,

–Midnite

I finally got this working with the following code:

    private void SelectButton(int controlIndex)
    {
        if (controlIndex < _buttons.Count)
        {
            Button button = _buttons[controlIndex];
            if (button != null)
            {
                EventSystem.current.SetSelectedGameObject(button.gameObject, new BaseEventData(EventSystem.current));
            }
        }
    }

7745610--974097--upload_2021-12-17_21-7-53.png

2 Likes