Press a UI button with code

I want to press a toggle button from code and have all the things happen the same as if a user pressed the button. e.g. transitions happen, toggle group notified, actions linked to button fire, etc. I am hoping for a general solution to simulating UI events.

Is there a way to inject a UI event in to unity?

[edit] To clarify
I want to

A)cause the button to be clicked by my code

not

B)cause my code to be called by clicking the button.

Cheers,
Grant

HI
You can use GUI Button, Here is the code snippet which i have given. I hope it helps you bit.

public class SampleClass : MonoBehaviour {
public Texture sampTexture;
private bool textToggle = false;
private bool imageToggle = false;
void OnGUI() {
if (!sampTexture) {
Debug.LogError(“Please assign a texture in the inspector.”);
return;
}
textToggle = GUI.Toggle(new Rect(10, 10, 100, 30), textToggle, “A Toggle text”);
imageToggle = GUI.Toggle(new Rect(10, 50, 50, 50), imageToggle, sampTexture);
}
}
So that you can change the button state and text on every click.

Simpliestway is without using UIevent, but UnityEvent with same methods in event list

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;

public class EventUnity : MonoBehaviour {
	public UnityEvent ButtonEvents;	//use UnityEvent as UIEvent
	public Button YourButton;		//emulated button. or you can use this 'gameObject'

	void Update () {
		if ((YourButton.onClick)||(Input.GetKey(KeyCode.Space))) //or something else
			ButtonAction ();
		}
		void ButtonAction(){
			ButtonEvents.Invoke ();
		}
}

this is what worked for my toggle button.

myButton.Select();
 myButton.OnSubmit();

for setting a toggle correctly. Note this will execute the toggle events just like pushing.

using UnityEngine.UI;

//assign the button here
public Button myButtonA;

void Start(){
// assign the function u need here
myButtonA.OnClick.AddListener(DoSth());

}


void DoSth(){
//do what you want here
}

Hope this helps :slight_smile: . wink