Pro_Unit

CoroutineTest

Jan 3rd, 2022 (edited)
585
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.19 KB | None | 0 0
  1. using System;
  2. using System.Collections;
  3.  
  4. using UnityEngine;
  5. using UnityEngine.InputSystem;
  6. using UnityEngine.UI;
  7.  
  8. public class CoroutineTest : MonoBehaviour
  9. {
  10.     public Image BarImage;
  11.     private Coroutine _fillAmountCoroutine = null;
  12.  
  13.     [SerializeField] private float _decreaseStep = 0.2f;
  14.     [SerializeField] private float _defaultEndValue = 1f;
  15.     private float _endValue = 1f;
  16.  
  17.     private void Start()
  18.     {
  19.         ResetEndValue();
  20.     }
  21.  
  22.     public void ResetEndValue()
  23.     {
  24.         _endValue = _defaultEndValue;
  25.     }
  26.  
  27.     private void Update()
  28.     {
  29.         if (Mouse.current.leftButton.wasPressedThisFrame)
  30.         {
  31.             if (_fillAmountCoroutine != null)
  32.                 StopCoroutine(_fillAmountCoroutine);
  33.  
  34.             IEnumerator doFillAmount = DoFillAmount(BarImage, 0f, _endValue, 1f);
  35.  
  36.             _fillAmountCoroutine = StartCoroutine(doFillAmount);
  37.  
  38.             _endValue -= _decreaseStep;
  39.  
  40.             if (_endValue <= 0)
  41.                 ResetEndValue();
  42.         }
  43.     }
  44.  
  45.     private IEnumerator DoFillAmount(Image image, float start, float end, float duration)
  46.     {
  47.         float elapsed = 0.0f;
  48.         while (elapsed < duration)
  49.         {
  50.             image.fillAmount = Mathf.Lerp(start, end, elapsed / duration);
  51.             elapsed += Time.deltaTime;
  52.             yield return null;
  53.         }
  54.  
  55.         image.fillAmount = end;
  56.     }
  57. }
Add Comment
Please, Sign In to add comment