Display a number counting towards the target number | Unity Game Engine


Count2Target.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
 
[RequireComponent(typeof(Text))]
public class Count2Target : MonoBehaviour
{
    public float countDuration = 1;
    Text numberText;
    float currentValue = 0, targetValue = 0;
    Coroutine _C2T;
 
    void Awake()
    {
        numberText = GetComponent<Text>();
    }
 
    void Start()
    {
        currentValue = float.Parse(numberText.text);
        targetValue = currentValue;
    }
 
    IEnumerator CountTo(float targetValue)
    {
        var rate = Mathf.Abs(targetValue - currentValue) / countDuration;
        while(currentValue != targetValue)
        {
            currentValue = Mathf.MoveTowards(currentValue, targetValue, rate * Time.deltaTime);
            numberText.text = ((int)currentValue).ToString();
            yield return null;
        }
    }
 
    public void AddValue(float value)
    {
        targetValue += value;
        if (_C2T != null)
            StopCoroutine(_C2T);
        _C2T = StartCoroutine(CountTo(targetValue));
    }
 
    public void SetTarget(float target)
    {
        targetValue = target;
        if (_C2T != null)
            StopCoroutine(_C2T);
        _C2T = StartCoroutine(CountTo(targetValue));
    }
}