- Home /
Lags, when i clicked several time on button
I want to change text when i click on button, but after i click several times game started lagging.
using System.Collections; using System.Collections.Generic; using System.Globalization; using UnityEngine; using UnityEngine.UI;
public class MiltiplayerButton : MonoBehaviour { public Text x;
public Button multi;
void Start()
{
multi.onClick.AddListener(buy10);
}
void buy1()
{
x.text = "1";
multi.onClick.AddListener(buy10);
}
void buy10()
{
x.text = "10";
multi.onClick.AddListener(buy100);
}
void buy100()
{
x.text = "100";
multi.onClick.AddListener(buy1);
}
} I know this code maybe to difficulty, but i dont know how to make simplify code.
Answer by Infenix · Aug 03, 2020 at 02:33 PM
I don't get what you're trying to do but what happens is that each time you click your button, you add a new listener. So the first time, you have a listener on buy10. If you click, you will have this listener and a new listener on buy100. If you click once more, you still have those two, plus a new one on buy100 and another on buy1. You are never removing the listeners you had on your button, so the amount of listeners at run time gets exponential with several clicks, making th whole thing lagging.
To solve it, you should consider removing them (if possible ?) when adding another, or turning off all of them but the one active, or having one listener and using attributes to keep tracking where you are in those numbers. I guess this doesn't break everything as the latest added listener will be the one you asked to add.
Your answer
Follow this Question
Related Questions
How to make on/off-like gui-button? 3 Answers
Screen scaling causing text to be outside button 0 Answers
why is my text not changing? [please help] 2 Answers
Change Text of GUI Button from Script 2 Answers