简体   繁体   中英

Unity UI Button has insane transition state behaviour - it remains highlighted after being clicked

It took me a while to figure out the problem with Unity UI Button Transition:

Problem: I hover on the button object, it goes to highlighted state, that's Fine. If I press mouse on button and it goes to pressed state then I move mouse outside of button so its no longer over button. The button goes to highlighted state instead of normal state. I need to click in empty space to get the normal state of button.

TLDR:

This is the default behaviour for a Button element in Unity - it retains focus after the initial interaction, causing it to show the Highlighted Color. Clicking away clears the focus, so it no longer becomes highlighted then.

To change this behaviour, you can switch the Navigation setting.

在此处输入图片说明

Currently, it's set to Automatic . According to the documentation , the option you want to use instead is None , which results in:

No keyboard navigation. Also ensures that it does not receive focus from clicking/tapping on it.

Hope this helps! Let me know if you have any questions.

If you want to use keyboard navigation and also get rid of this problem you can add this function to update:

void Update()
{
    if (Input.GetMouseButtonUp(0))
    {
        EventSystem.current.SetSelectedGameObject(null);
    }
}

To retain keyboard automatic navigation, you probably want to inherit from IPointerExitHandler and deselect on exit:

public void OnPointerExit(PointerEventData data)
{
    EventSystem.current.SetSelectedGameObject(null);
}

You could add checks to only deselect gameObject if already selected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM