Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Help UI button why is it clicking many times

Discussion in 'UGUI & TextMesh Pro' started by Netzeus, Jun 3, 2015.

  1. Netzeus

    Netzeus

    Joined:
    Oct 12, 2012
    Posts:
    5
    Why is this not working when I click the button it click many time ? please help someone

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

    public class BUTTONBOOSTSCRIPT : MonoBehaviour {

    public Button ClickBoost;
    public int boostpower=0;

    void OnGUI(){

    ClickBoost.onClick.AddListener(CLICKBOOST);}

    void CLICKBOOST(){

    boostpower+=10;}
    }
     
  2. TrickyHandz

    TrickyHandz

    Joined:
    Jul 23, 2010
    Posts:
    196
    The problem is that you are adding the listener in OnGUI(). OnGUI() can be called multiple times per frame, resulting in the method being added multiple times. Also, you should not be used for anything with the new GUI system...at this point it is most suited for custom editor work only. If you absolutely need to add the listener via code something like this would be better:

    Code (csharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4. using UnityEngine.UI;
    5.  
    6. public class BUTTONBOOSTSCRIPT : MonoBehaviour
    7. {
    8.  
    9.     public Button ClickBoost;
    10.     public int boostpower=0;
    11.  
    12.     void Start()
    13.     {
    14.         ClickBoost.onClick.AddListener(CLICKBOOST);
    15.     }
    16.  
    17.     void CLICKBOOST()
    18.     {
    19.         boostpower+=10;
    20.     }
    21. }
    22.  
    However, I highly recommended using the OnClick UnityEvent that is available in the inspector for the Button GameObject.
     
    Netzeus and SimonDarksideJ like this.
  3. Netzeus

    Netzeus

    Joined:
    Oct 12, 2012
    Posts:
    5
    Great thanks a lot :)
     
    TrickyHandz likes this.
  4. SimonDarksideJ

    SimonDarksideJ

    Joined:
    Jul 3, 2012
    Posts:
    1,685
    Beat me to it there @TrickyHandz
    That code was effectively adding a listener every frame and would likely cause one helluva memory leak.
     
    TrickyHandz likes this.