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(); });

This is nice manual for your question: c# - Unity new UI - Dynamically change the functions called by GUI elements - Game Development Stack Exchange

Try calling a method that is located within the GameMaster script and have that method reference your Player class. For example:


menu_button.onClick.AddListener(() => Pause());


public void Pause()
      menu_obj = GameObject.Find ("Pause Button");
      player.GetComponent<GUI_HUD> ().pause();