Hello I’m making three button which gives upgrade when you click
and type of upgrade is randomly chosen when level up
So when level gets up button name will randomly change
public void LevelUp()
{
for (int i = 0; i < 3; i++)
{
RandomDraw();
if (i == 0)
{
b1text.text = b;
}
else if (i == 1)
{
b2text.text = b;
}
else if (i == 2)
{
b3text.text = b;
}
}
}
and each button have script like this
void Update()
{
b = ThisText.text;
switch (b)
{
case "Add Gun Damage":
B1.onClick.AddListener(GunDamageUp);
b = "null";
break;
case "GunAUTO":
B1.onClick.AddListener(GunAuto);
b = "null";
break;
case "GunATS":
B1.onClick.AddListener(GunSpeedUp);
b = "null";
break;
}
}
so when I level up button text will change and script will put onClick one
is add gun damage then if I click button it increases damage
It works fine in first level up but when I get more level, button dosen’t work properly
It sometimes make wrong result (text says dmg up but when I click speed is up)
or get multiple upgrade (text says dmg up but dmg up + speed up)
I have no idea how to fix it
To the greatest extent possible, always treat all Unity properties and fields as write-only, especially if they are text.
Not only that but you are parsing this in Update() which means every single frame you are adding the listener… again and again and again… each one a separate listener connection.
In just one second you would have added 60 listeners, so clicking upgrade button ONCE will bang that delegate 60 times… or THOUSANDS of times.
Instead, structure your program so that you:
add a set of listeners ONCE (usually in OnEnable())
remove those listeners ONCE (usually in OnDisable())
the listener should ONLY connect to the button at a very abstract level (eg, “button 1”)
you decide in code what that means (button 1 means Gun damage up)
when you receive button 1 you decide “I must do Gun Damage up” and then you can ask:
→ is that legal right now?
→ if not, display something saying “NOPE”
→ if yes, then up the gun damage and display “DONE”
Note that only the first add / remove steps touch the button itself. Everything else is completely disconnected from Unity and doesn’t care. You could hook in a cheat key as well if you want, no other logic changes.