0
\$\begingroup\$

I am working on a game in unity where a user will click a button to gain coins and clicks over a lifetime of clicking the button but the code is making the clicks go up by a lot instead of just 1 each time it is clicked like here are the values returned the first 3 clicks 247 731 2111 anybody have an idea why it produces this behavior and how i can fix it?

using UnityEngine; using UnityEngine.UI; using System.Collections; public class GameManager : MonoBehaviour { public Button clicker; public Text coinsSec; public Text ltClicks; private float baseClick = 2; private float coins = 0; private float lifeTimeClicks = 0; private float coinsPerSec; private void Start(){ UpdateTxt (); } private void Update(){ UpdateTxt (); Clicker (); } private void Clicker(){ clicker.onClick.AddListener (delegate { coins += baseClick; lifeTimeClicks++; }); } private void UpdateTxt(){ coinsSec.text = "Coins/s: "; ltClicks.text = "Lifetime Clicks: " + lifeTimeClicks.ToString (); } } 
\$\endgroup\$

2 Answers 2

4
\$\begingroup\$

You are adding the listener function inside Clicker(), which is getting called from Update(). Update() happens every frame, which means every frame you are adding a new listener. If you click once, and it adds 256 to your coins, then that means you have 128 listeners waiting for that click (since a click adds 2). Try calling Clicker only once from Start instead of Update and see if that fixes your problem.

\$\endgroup\$
1
  • \$\begingroup\$ yep that fixed the issue thx i will accept once it allows me too \$\endgroup\$ Commented May 9, 2016 at 18:36
2
\$\begingroup\$

Short answer, move the call to Clicker to be in Start(),

Longer answer Update gets called once every frame (which ideally is at least 30 times per second), so by putting it in update you are registering a new delegate every frame. So after 10 frames, the anonymous delegate would get created 10 times. Meaning when you click the button, it would increment lifeTimeClicks by 10, then 20 frames later when you click the button again, the delegate will have been registered 30 times, causing the lifeTimeClicks to increase by 20

\$\endgroup\$

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.