- Home /
Unity 4.6 UI onClick listener doesn't work
Hello.
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 methodonClick' 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 {
[SerializeField]
private Button graphicsButton = null;
// Use this for initialization
void Start () {
graphicsButton.onClick.AddListener(() => {
Debug.Log("test1");
Debug.Log("test2");
});
}
// Update is called once per frame
void Update () {
}
}
graphicsButton is initialized to null, it is private, where and when are you setting it to an instance of type Button?
Error in line 14, which is graphicsButton.onClick.AddListener(() => {
Yes Landern is right. You probably wanted to set it to public and assign in in the inspector via drag&drop. But you can also use the event trigger to assign a button a function and not vice versa
why you don't use event trigger component ? do you know what this component do ?
Answer by lodendsg · Feb 04, 2015 at 08:29 PM
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.
Answer by Mmmpies · Dec 26, 2014 at 03:52 PM
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()
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.
Answer by jenci1990 · Dec 26, 2014 at 04:13 PM
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;
Your answer
Follow this Question
Related Questions
Unity 4.6: Position jumps when switching Canvas render mode from Overlay to camera in code 0 Answers
How can i access the Image renderer? 1 Answer
[4.6] Sound won't play either on Unity Editor or in Play Mode 3 Answers
Simple UI not appearing once deployed to iOS (4.6.2) 1 Answer
Unity UI 4.6 - Programmatically adding events - EventTrigger.delegates is null 0 Answers