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

Resolved Buttons single click

Discussion in 'Getting Started' started by Dreshpack, Apr 3, 2022.

  1. Dreshpack

    Dreshpack

    Joined:
    Aug 28, 2021
    Posts:
    4
    I have a button and i want my function to do only one time when I press the button and I don't want to use the inspector
    public Button lvlUpButton;
    private int priceOfLvlUp = 10;
    bool lvlUpEndCheck = true;
    void Update()
    {
    lvlUpButton.onClick.AddListener(testDebug);
    }
    void testDebug()
    {
    Debug.Log("fu");
    }
    if i press the button i get 1+ thousand times my function
    upload_2022-4-3_16-41-4.png
    Should I use another function instead of Update or I should use coroutine I think if I use coroutine if u press the button more than a time i will use in coroutine u will get the same result. Or i should make my button not interactable after it will do for a second. Sorry for my bad English if u didn't get smth ask me please
     
  2. Vryken

    Vryken

    Joined:
    Jan 23, 2018
    Posts:
    2,106
    Yes. You only need to assign a listener once, not every frame. Your application will endlessly consume memory assigning an infinite number of listeners until it runs out of memory & crashes.

    Assign the listener once in a method like
    Start
    or
    Awake
    .
     
    Dreshpack likes this.
  3. Dreshpack

    Dreshpack

    Joined:
    Aug 28, 2021
    Posts:
    4
    Thank you very much