Unity 4.6 UI onClick listener doesn't work


Whenever I try to add a listener to a button it just gives me an error:

Assets/test.cs(14,32): error CS1061:
Type Button' does not contain a definition for onClick’ and no
extension method onClick' of type Button’ could be found (are you
missing a using directive or an
assembly reference?)

With this script:

using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System.Collections;

public class test : MonoBehaviour {

	private Button graphicsButton = null;

	// Use this for initialization
	void Start () {
		graphicsButton.onClick.AddListener(() => {
	// Update is called once per frame
	void Update () {

<< you don’t need listener >>

create a new function like this in a script :

function clickme()
{ Debug.Log("test1"); Debug.Log("test2"); }

then assign it to your Onclick() event in your button !

Both @Mexallon and @Landern are right you haven’t set that variable to an actual button.

either do as they suggested and make the graphicsButton public and then drag a button onto it in the inspector from your canvas.

Or add a button to,your canvas and rename it testButton. Then in Start()

    graphicsButton = GameObject.Find("testButton").GetComponent<Button>();

Then do you your graphicsButton.onClick.AddListener

It just needs to know which button you’re trying access even if there’s only one button in the scene.

Maybe you have script with name “Button”. Try UI.Button. And “graphicsButton” is always null, so make it public and assign in inspector.

public UI.Button graphicsButton = null;

Had the same issue re “Button does not contain ‘onClick’” turns out there is more than one Button class and oddly Visual studio didn’t give me the usual ambiguous warning … no idea how that could be but all the same using the fully qualified name resolved e.g. UnityEngine.UI.Button when declaring the class or casting.