Unity 4.6: GetComponent().onClick... how do you add an event to button click?

The problem is simple: new UI system has cool buttons, but if I want to really use them I need to be able to add onClick events by code. Why? Well if I know I can atach script to the button in the editor, but most of the stuff must be created after the game is started. And even if I go around it premaking all the buttons it would be nice to have just one script… not multiple scripts for every button.

in short: how do I modify/add event to this thing?
GetComponent().onClick

assuming a GameObject myButton with a Button component on it:

C#

myButton.GetComponent<Button>().onClick.AddListener(() => { someFunction(); otherFunction(); }); 

for access to UI classes such as Button add using UnityEngine.UI; at the top of the script

Don’t forget to add:
using UnityEngine.UI;

i have some problem, because i’m using this function, in void Update, and how can i get, only one call function? not anymore callback

void Start()
    {
        myselfButton = GetComponent<Button>();
    }

	void Update () {
        if (Input.GetMouseButtonUp(0))
        {
            myselfButton.onClick.AddListener(() => actionToMaterial(index));
        }
	}

becuase, when i click on button in consoles write me any debug, but i need only one call this function. thanks

how to add events from another scripts ?

first create class for button in my case (ToolButton.cs) then add this script like below

		currentButton = Instantiate(tool) as GameObject;
		button = currentButton.AddComponent<ToolButton>();
		button.tool = btn;
		button.counter = counter;

in ToolButton scripts on Start() function you need to add Addlistener to each button
UnityEngine.Events.UnityAction action = () => { Play();};
GetComponent ().onClick.AddListener (action);

public Transform DebugPanel;
public GameObject DebugText;

    void Start()
    {
        var db = new DataService();
        foreach (var ss in db.DBUsers)
        {
            GameObject Local = Instantiate(DebugText);

            Local.GetComponentInChildren<Text>().text = "User: " + ss.idUsers + " " + ss.Login;
            Local.GetComponentInChildren<Button>().onClick.AddListener(delegate () { ShowWhatWasCliked(ss); });
            Local.transform.SetParent(DebugPanel);
        }
    }

    private void ShowWhatWasCliked(DBUsers ss)
    {
        Debug.Log(ss.Login);
    }