Skip to content

Instantly share code, notes, and snippets.

@buijldert
Last active June 2, 2017 06:49
Show Gist options
  • Save buijldert/369c6061d2d761abe98a37263ed565ab to your computer and use it in GitHub Desktop.
Save buijldert/369c6061d2d761abe98a37263ed565ab to your computer and use it in GitHub Desktop.
using System;
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
public class IncreaseScoreOverTime : MonoBehaviour
{
//The text component that the score will be displayed on.
[SerializeField]
private Text _scoreText;
//The time it will take to update the score.
[SerializeField]
private float _updateTime = 1f;
//The current displayed score.
private float _score;
//The actual score.
private float _updatedScore;
//The coroutine used to update the score.
private Coroutine _lerpScoreCoroutine;
/// <summary>
/// Starts the coroutine to update the score to the updated score.
/// </summary>
/// <param name="scoreMutation">The amount that is added to the score.</param>
private void UpdateScore(float scoreMutation)
{
if (_lerpScoreCoroutine != null)
{
StopCoroutine(_lerpScoreCoroutine);
}
_updatedScore = _updatedScore + scoreMutation;
_lerpScoreCoroutine = StartCoroutine(LerpScore());
}
/// <summary>
/// Lerps the score from score to updated score and displays it on the text component.
/// </summary>
private IEnumerator LerpScore()
{
float elapsedTime = 0;
while (elapsedTime < _updateTime)
{
_score = Mathf.Lerp(_score, _updatedScore, (elapsedTime / _updateTime));
_scoreText.text = (Math.Round((decimal)_score, 0)).ToString();
elapsedTime += Time.deltaTime;
yield return new WaitForEndOfFrame();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment