Search code examples
unity-game-engineincrementunity-ui

Unity-Press Button to slowly increment number


I'm trying to do something like the old GTA style money system like in Gta vice city or san andreas. So when you add or obtain money, the number doesn't just jump to the result. It slowly increments till the value added is done.

I want to do this by clicking buttons, so one button will add 100 dollars and other will subtract 100 dollars and so on.

The buttons don't seem to be playing nice with update and Time.deltatime.


Solution

  • To slowly increment a number over the time, you can do something like this:

        public float money = 100;
        public int moneyPerSecond = 25;
        public int moneyToReach = 100;
        bool addingMoney = false;
    
        private void Update()
        {
            if (addingMoney)
            {
                if (money < moneyToReach)
                {
                    money += moneyPerSecond * Time.deltaTime;
                }
                else { addingMoney = false; money = Mathf.RoundToInt(money); }
            }
        }
    
        public void addMoney()
        {
            moneyToReach += 100;
            addingMoney = true;
        }