UI Button Script Spamming

So i created a button in UI and made a script for it as i want the button to instantiate an object.

I had a problem with the fact 50 objects got created at once. I then tried Print(“Test”) on the button press and it spammed it around 50 times in 1 click.

I realized this is because its on void Update()

void Update () {
mainobjectsbutton.GetComponent<Button>().onClick.AddListener(() => {


			print ("test");


		});
}

What should I do to get around this and make it so it sends just one message? I have tried bools however it just does the same thing.

Thanks for any help

Hey, I think your problem is, that you add the event listener in the update method. Remember Update gets called every frame. Therefore you add a new event Listener every frame. Your button will then execute the print multiple times.
A simple fix would be to put your code in the Start Method for example.

I had the same issue this week with new UI. I tried to understand the reason, and I notice that if I hold the button a lot of “click” are detected… Really weird.

Anyway, yesterday I decide to solve with a simple solution, but a little ugly and obviously unnecessary if the Button was working as expected.

private float lastClick = 0;
public void OnButtonCreateGame(){
        if (lastClick > (Time.time - 1f)) return  ;
	    lastClick = Time.time;
        ... //do what need to do
}

That’s all… Works perfect in my case… The user can click once per second.
I hope that this could help you.