OnClick on button from code

I can’t find how to detect clicks on a button from code, like mouse down, mouse up after mouse down?

Thanks

2 Likes

Don’t use Button, use EventTrigger instead.

2 Likes

This seems counter-intuitive as the first time i hear about it. Is there any example?

Thanks!

Like this?

void Start()
    {
        Button b = gameObject.GetComponent<Button>();
        b.onClick.AddListener(delegate() { StartGame("Level1"); });
    }
   
    public void StartGame(string level)
    {
        Application.LoadLevel(level);
    }
8 Likes

Not working here =(

public void SetupButton () {
     var button = transform.GetComponent<Button>();
     button.onClick.AddListener(delegate () { this.ButtonClicked(); });
}

public void ButtonClicked () {
     _buildStructureGUI.SelectedPool = _structurePool;
}
1 Like

Do you need to set it up from code? e.g. Do you have procedurally generated buttons?

Setting it up in the Editor is much easier (and the ‘expected’ use).

Its procedurally =/

Have you tried referring directly to the function as a delegate, as opposed to creating an in-line delegate that calls the function?
(I haven’t, but I feel like this should work)

public void SetupButton () {
     var button = transform.GetComponent<Button>();
     button.onClick.AddListener(this.ButtonClicked);
}

public void ButtonClicked () {
     _buildStructureGUI.SelectedPool = _structurePool;
}

I’m not sure how one would add parameters to this. I would’ve expected that AddListener would have a second parameter that could become the callback’s parameter (equivalent to that third ‘box’ in the Inspector).

I’ve tried too, but without success … I have the impression that it is necessary to mark the delegate as persistence … But I do not know how …

Same thing, still trying to figure out how to have the handler function receive the actual button, or anything else as a parameter.

I think it can be done using the new UnityAction, but I can’t manage to get it right.

You just need to remove the parentheses from where you are setting delegate…

This is working fine for me…

    public void setupBtn()
    {
        string param = "bar";
        btn.GetComponent<Button>().onClick.AddListener(delegate { btnClicked(param); }); 
    }
       
    public void btnClicked(string param)
    {
        Debug.Log("foo " + param);
    }

Outputs “foo bar”, as one would expect.

9 Likes

Thank you ldb: it works.

For curiosity, in the Editor Inspector, the OnClick listener of the button does not appear. Is it normal?

1 Like

I noticed the same problem. Listener does not appear, but it works. Looks like the list isn’t being refreshed. I reported this as a bug.

thanks Amaranth

That reminds me! Found an easier way to do what we all seem to be trying to do. It turns out that Unity 4.6 has a built-in feature for this. This is how I used it:

  1. In the Project Tab, create a new script called MyEventListener.
  2. Paste this code into the script:
using UnityEngine;
using UnityEngine.EventSystems;

public class MyEventListener : MonoBehaviour, IPointerClickHandler
{
    private float clickTime;            // time of last click
    private int clickCount=0;         // current click count
    public bool onClick = true;            // is click allowed on button?
    public bool onDoubleClick = false;    // is double-click allowed on button?
    
    public void OnPointerClick(PointerEventData data)
    {        
        // get interval between this click and the previous one (check for double click)
        float interval = data.clickTime - clickTime;

        // if this is double click, change click count
        if (interval < 0.5 && interval > 0 && clickCount != 2)
            clickCount = 2;
        else
            clickCount = 1;

        // reset click time
        clickTime = data.clickTime;
            
        // single click
        if (onClick && clickCount == 1)
        {
            // enter code here
        }
    
        // double click
        if (onDoubleClick && clickCount == 2)
        {
            // enter code here
        }
    
}
  1. Drag this script on to your button game object (or attach it via code).
  2. Set the onClick and onDoubleClick bools (you may want one click on some objects, double-click on others, etc)

(updated with small changes)

2 Likes

@AntFitch Will this script work for Touch Input. if not what changes i should make ?

The script should work with touch.

But how the click is associated with touch ? im bit confused here :frowning: . well atleast i should try it out first hehe

A ‘click’ is a higher level concept. It’s when you down and up on the same alement. So a ‘click’ for a touch is when you put your finger down and up on the same element.

Thanks for the awesome code amaranth! I know it’s a year later and big changes have come about, but in Unity 5.1 I got the following error. My hack(see attached script) was to hit the button and have it play an Animator trigger animation. Scripting is not my forte as you can tell. I have an ‘Idle’ animation that is transitioned to a ‘Throw’ animation. The ‘Throw’ animation has a trigger parameter. Every time the button is hit, the 3D player throws a ball. It would be a milestone to get this part working. Thanks in anticipation

2257720–150934–MyEventListener.cs (996 Bytes)

1 Like