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

Button.onClick.AddListener(() => Attack()); isn't running function math correctly

Discussion in 'UGUI & TextMesh Pro' started by MJG1123, May 31, 2015.

  1. MJG1123

    MJG1123

    Joined:
    Apr 12, 2015
    Posts:
    24
    I have a menu with multiple functions and settings so I am using the below code to switch methods via state, but something is going wrong with the math except when I associate the method with an input, so I know there's something wrong with the OnClick.AddListener I am using. Here's a video

    Code (CSharp):
    1.  switch(currentBattleState){
    2. case (BattleStates.PLAYERCHOICE):
    3. // Seupt Battle Function
    4.        
    5. Button1.SetActive(true);
    6. Button1text.text = "WaterPunch";
    7. Button1b.onClick.AddListener(() => Attack());
    8. //----------------------------------------------------------
    9.  
    10.      if (Input.GetKeyDown(KeyCode.W))
    11.          {
    12.              Attack();
    13.          }
    14. //-----------------------------------------------------------
    15.  
    16. public void Attack()
    17.      {
    18.          enemyHealth.battleEHealth -= 2 + (3 * levelUp.currentPlayerLevel);
    19.    
    20.      }    
     
  2. Sbizz

    Sbizz

    Joined:
    Oct 2, 2014
    Posts:
    250
    Because you don't clear your list. So, every time you click on the button, you add the method "Attack()" to the list. The first time, you'll have only one item in the list, then 2, then 3, etc.

    You need to clear your list before adding something else (except if you want to stack everything).

    Button1b.onClick.delegates.Clear();