- Home /
4.6+ GUI, assign OnClick() from script.
I have just added a GameMaster object to my scene which will instantiate and set all players and all relevant objects and linkage.
How do I connect the (newly) added Canvas buttons to the specific function that I need called.
I am trying to call a method called pause() that exists on the player as a script (GUI_HUD) from a completely different object than either of the two (not canvas or gui_hud)
player = GameObject.Find ("Player");
menu_obj = GameObject.Find ("Pause Button");
_script = player.GetComponent<GUI_HUD> ();
Button menu_button = menu_obj.GetComponent<Button> ();
menu_button.onClick.RemoveAllListeners ();
menu_button.onClick.AddListener (delegate { _script.pause(); });
Answer by Denvery · Mar 12, 2015 at 10:08 PM
Hello! This is nice manual for your question: http://gamedev.stackexchange.com/questions/83027/unity-4-6-gui-dynamically-change-the-functions-called-by-gui-elements
Answer by brentstrandy · Mar 13, 2015 at 10:56 AM
Try calling a method that is located within the GameMaster script and have that method reference your Player class. For example:
GameMaster.cs
menu_button.onClick.AddListener(() => Pause());
Player.cs
public void Pause()
{
menu_obj = GameObject.Find ("Pause Button");
player.GetComponent<GUI_HUD> ().pause();
}
Button menu_button;
GameObject menu_obj;
menu_obj = GameObject.Find ("Pause Button") as GameObject;
menu_button = menu_obj.GetComponent<Button> ();
UnityEngine.Events.UnityAction action = () => { this.pause(); };
menu_obj.GetComponent<Button>().onClick.RemoveAllListeners();
menu_obj.GetComponent<Button>().onClick.AddListener(action); // <- does not work
menu_button.onClick.AddListener(action);
menu_button.interactable = false; //<- works
menu_obj.SetActive (true); //<- works