Rollover / button press effect via code

Hi there.

I’m wondering if anyone knows a way to get the standard UI Button to appear as if it’s being pressed / moused over even when it isn’t?

Basically, I have created a series of buttons to allow the user to select multiple choice answers to a question and have got the buttons working for both button presses with a mouse / touchscreen as well as input via a physical keyboard or game pad.

The button uses a 9 slice background and displays different background images for three states.

What I want is for the visual part of the button pressed effect to trigger when a certain physical key is pressed on an external keyboard, in the same way it is if I press it with a mouse click or tap on a mobile device. The function I’m running onClick works fine, but the visual change seems to be part of the built-in functionality of the button and I can’t find a way to access it or any info in the docs / on these forums.

I know I can hack it and have an overlay image that is hidden until the related keyboard key is pressed, that then displays on top of the button at the same size / location, but I wondered if there was a cleaner way of doing this that just links into the button press functionality and triggers the background image change.

Thanks,

Ian

Answered my own question… this does the trick

// Assumes the sprite state for the button has been set up already and images assigned to the various states
// myButtonGameObject is the game object the button is attached to

Button button = myButtonGameObject.GetComponent<Button>();
SpriteState spriteState = new SpriteState();
spriteState = button.spriteState;
button.image.sprite = spriteState.pressedSprite;