how to change a buttons function with a script?

so i got this working already with this line of code

     x.GetComponentInChildren<Button>().onClick.AddListener(delegate{ use_item(name); }) ;

my problem is when i click the button in question it will keep calling the function as long has its clicked.
basically after holding the mouse down for 3 seconds it will call the function 107ish times (from my debug log).

how do i stop that?
how do i set my button to call a function only once?

on a side note I found “delegate” while looking up syntax but I can not find any thing explaining
what it dose. if any one can tell me what it does that would be appreciated.

i forgot to mention that I am working with a list of buttons and that line of code would update the name (string variable) in each one.

so about 9 buttons in all each call the same function but send its own string
and i have the ability to change that string in game. that is what i’m trying for

A delegate is a method you subscribe to an event. When you work with C# events, you declare a delegate that represents the signature of the method (the parameters it must be passed), then you subscribe methods that match that signature/delegate.
If you don’t already implement such method, you can build a delegate and pass it. This is what you do here :

x.GetComponentInChildren<Button>().onClick.AddListener(delegate{ use_item(name); }) ;

delegate {} is a method with no name that you pass.
The only problem with this, is that you have no reference to it to later unsubscribe it with UnityEvent.RemoveListener.
Your only option then is to use UnityEventBase.RemoveAllListeners to remove all delegates.

Consider doing this :

x.GetComponentInChildren<Button>().onClick.AddListener (OnUseItem);
public void OnUseItem ()
{
    use_item(name);
}

Which allows you to later remove it with :

x.GetComponentInChildren<Button>().onClick.RemoveListener (OnUseItem);

Hope this clarifies things a bit.

Although, I’m pretty sure there’s another problem as a button shouldn’t be called 100 of times if you simply keep it pressed, as onClick event is called when you release the button.

ok that dose not let me dynamically change the name variable and its still calling the function to much so I’m back to were i was