Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice

Question Click Button once but trigger the event twice

Discussion in 'UGUI & TextMesh Pro' started by wechat_os_Qy00M9veuJsy7HfHRQLvYOPQQ, Oct 17, 2023.

  1. wechat_os_Qy00M9veuJsy7HfHRQLvYOPQQ

    wechat_os_Qy00M9veuJsy7HfHRQLvYOPQQ

    Joined:
    Oct 17, 2023
    Posts:
    1
    I've implemented a toggle button that initiates the game when clicked and halts the game when clicked again. The button's text also changes accordingly. However, when I run the code as provided, each time I click the button, the ToggleGame() function appears to execute twice. Consequently, the button text remains "STOP," and the isMoving variable consistently remains true.

    Code (CSharp):
    1.  void Start()
    2.     {
    3.    
    4.         if (toggleButton != null)
    5.         {
    6.             toggleButton.onClick.AddListener(ToggleGame);
    7.         }
    8.  
    9.         StartGame();
    10.  
    11.     }
    12.  
    13. public void StartGame()
    14. {
    15.         isMoving = true;
    16.         //init some setting here
    17.  
    18.  
    19. }
    20.  
    21. void Update()
    22.     {
    23.         if (isMoving)
    24.         {
    25.            //run the game
    26.         }
    27.     }
    28.  
    29. public void ToggleGame()
    30.     {
    31.         if (!isMoving)
    32.         {
    33.             StartGame();
    34.             UpdateButtonText("Stop");
    35.         }
    36.         else
    37.         {
    38.             isMoving = false;    
    39.             CheckWinCondition();
    40.             UpdateButtonText("Start");
    41.         }
    42.   }
    Can anyone help me on this? Thank so much, I have stuck in this problem all day long.
     
    Last edited: Oct 18, 2023