How to trigger a button click from script

I am trying to make a “Game Over” screen appear when the player health bar reaches zero. Which I was able to do… However I also want to stop the music and perform a couple other functions. I know I can do this via the script by referencing other objects, but thus far I’ve been using the new version 4.6+ GUI On Click() events from the Inspector which I like because they’re easy to change and intuitive… How can I set up a list of events in the Inspector for when health bar reaches zero?

I’ve tried using a slider for the health bar, which works visually… but I only want those events to happen when the fillAmount is zero, not every time it changes.

So then I tried attaching a button to the health bar (unchecked interactable of course) and I am trying to figure out a way to trigger a button press when the fillAmount of the health bar = 0. Is it possible to trigger a button press from script? Any help would be greatly appreciated.

Here is my latest failed attempt at triggering a button press from my script:

void Update() {
if (playerHealth.fillAmount == 0) { // playerHealth is the healthbar Image.
	pHealth.SendMessage ("OnClick"); // pHealth is a button attached to the image
	loseScreen.SetTrigger ("youLose"); // loseScreen is a UI panel that slides in.
	Time.timeScale = 0;
}

Make sure you have a reference to the Button component and write:

referenceToTheButton.onClick.Invoke();

http://docs.unity3d.com/ScriptReference/UI.Button.html

http://docs.unity3d.com/ScriptReference/UI.Button-onClick.html

http://docs.unity3d.com/ScriptReference/UI.Button.ButtonClickedEvent.html

Using the onClick event triggers the actions on that event, but it doesn’t do other button press effects such as colour changes or animations. This will send the submit message to the button’s game object which is what happens when you trigger a focussed button with a keypress or game pad.

ExecuteEvents.Execute(button.gameObject, new BaseEventData(eventSystem), ExecuteEvents.submitHandler);

It’s not particularly well documented. I found it by inspecting the source code for the UI.

As of Unity 2019.2.1, you can Focus a button with:

yourButton.Select();

Note that it does not “click” it. Just Focus.

you could also do a collision check, but thats very basic and simple so only if you’re desperate