- Home /
Button.onClick.AddListener
Hi everybody, im using this code:
 public int index;
     private Button myselfButton;
 
     void Start()
     {
         myselfButton = GetComponent<Button>();
     }
 
     void Update () {
         if (Input.GetMouseButtonUp(0))
         {
             myselfButton.onClick.AddListener(() => actionToMaterial(index));
         }
     }
 
     void actionToMaterial(int idx)
     {
         Debug.Log("change material to HIT  on material :  " + idx);
     }
and when i click on the button, console write me some debug, in one time, but i need call this function only one. How can i do it? Anybody knows what im doing wrong? Thanks
               Comment
              
 
               
              Answer by HarshadK · Apr 02, 2015 at 11:55 AM
Just add the listener to your button in start only and not required to be done inside Update on each click.
  public int index;
  private Button myselfButton;
 
  void Start()
  {
      myselfButton = GetComponent<Button>();
      myselfButton.onClick.AddListener(() => actionToMaterial(index));
  }
 
  void actionToMaterial(int idx)
  {
      Debug.Log("change material to HIT  on material :  " + idx);
  }
You should also RemoveListener when gameobject is destroyed or disabled
  void Destroy()
  {
       myselfButton.onClick.RemoveListener(() => actionToMaterial(index));
  }
Your answer
 
 
              koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                
