The clicked button runs the command a lot times

I made a code and an UI. However, when I clicked the button, the total somtimes will increased to 15678 from 0, or 2346 from 0. But I want it plus 1 or 5 only. How can I solve it?

Button buttonA, buttonB;
public int total

void Start()
{
total = 0;
var root = GetComponent<UIDocument>().rootVisualElement;
buttonA = root.Q<Button>("buttonA")
buttonB = root.Q<Button>("buttonB")
}

void Update()
{
buttonA.clicked += CountA;
buttonB.clicked += CountB;
}

void CountA()
{
Count(1)
}
void CountB()
{
Count(5)
}

void Count(int num)
{
total += num;
}
void Update()
{
buttonA.clicked += CountA;
buttonB.clicked += CountB;
}

You are adding more and more callbacks each frame, that’s why Count is getting called multiple times. The update is not the right place for initialization - move this code block from Update to Start and it should work.

2 Likes