Keypress triggers toggle
I have two checkbox toggles that work fine. My problem is that the spacebar and Enter keys act as if I had clicked on one of the toggles. I think the last toggle touched is the one affected. Is there are way to disable the effect of the key press?
Answer by marioguttman · Jan 30, 2018 at 11:27 PM
I answered my own question (or, at least found workaround) in case anyone is interested. Apparently the UI maintains a "focus" on the last item selected (clicked-on). Then the Enter and Spacebar keys act as if they were clicking on the element with the focus. The workaround is to add a dummy element (I used a button; it wouldn't work with a piece of text) and set the focus to that in the code.
public Button dummy; // Just used to set focus away from toggles
Then, in the toggle listener functions set the focus back to the button:
public void ShowVisitedToggleListener(bool value) {
if (value) {
...
} else
{
...
}
dummy.Select(); // Just to keep focus off of the toggles
// so that key presses don't affect them
}
When you get it all working you can just turn of the button in the Inspector. The code will still find it.
Your answer
![](https://koobas.hobune.stream/wayback/20220612151629im_/https://answers.unity.com/themes/thub/images/avi.jpg)