Question by
chris56728 · May 08, 2016 at 02:54 PM ·
c#uicanvasonclick
C# - Canvas UI addListener in code is not working
Hello guys,
I'm trying to add an onClick in code to a canvas UI button and i've tried 3 different approaches and none of them are working. Any suggestions on how to make this work?
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;
using System.Collections;
using TriviaQuizGame;
using TriviaQuizGame.Types;
public class OnClick_Button_Canvas : MonoBehaviour
{
public Button buttonPrefab; //default button
//private TQGGameController tqgameController;
private TQGGameController tqgameController2;
private int index = 0;
public void start()
{
GameObject go = GameObject.Find("GameController");
//TQGGameController tqgameController = (TQGGameController)go.GetComponent(typeof(TQGGameController));
TQGGameController tqgameController2 = new TQGGameController();
//TRIED 3 DIFFERERENT APPROACHES:
//buttonPrefab.onClick.AddListener(delegate { MyMethod(0); });
//buttonPrefab.GetComponent<Button>().onClick.AddListener(() => { MyMethod(index);});
buttonPrefab.onClick.AddListener(MyMethod(0));
}
public void MyMethod(int index)
{
Debug.Log("Button Clicked");
tqgameController2.ChooseAnswer(index);
}
}
Comment
Best Answer
Answer by chris56728 · May 08, 2016 at 04:16 PM
Figured this out!
There is a build in way to do this: using UnityEngine; using UnityEngine.Events; using UnityEngine.UI; using System.Collections; using TriviaQuizGame; using TriviaQuizGame.Types; using UnityEngine.EventSystems;
public class OnClick_Button_Canvas : MonoBehaviour, IPointerClickHandler
{
public Button buttonPrefab; //default button
//private TQGGameController tqgameController;
private TQGGameController tqgameController2;
private int index = 0;
public void start()
{
GameObject go = GameObject.Find("GameController");
//TQGGameController tqgameController = (TQGGameController)go.GetComponent(typeof(TQGGameController));
TQGGameController tqgameController2 = new TQGGameController();
}
public void OnPointerClick(PointerEventData data)
{
Debug.Log("Button Clicked");
tqgameController2.ChooseAnswer(index);
}
}
Your answer
Follow this Question
Related Questions
C# - Creating Canvas UI button on click in code 2 Answers
Canvas Structure for Different UI Panels 0 Answers
cannot find UI GameObject by script 1 Answer
Player Can't Interact With UI 3 Answers
Detecting a button click 1 Answer