Advertisement
RedBum

CounterScript

May 7th, 2024
564
0
Never
1
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.03 KB | None | 0 0
  1. using System.Collections;
  2. using UnityEngine;
  3. using UnityEngine.UI;
  4.  
  5. public class CounterScript : MonoBehaviour
  6. {
  7.     [SerializeField] private Text counterText;
  8.     private float counter = 0f;
  9.     private bool isCounting = false;
  10.     private Coroutine countCoroutine;
  11.  
  12.     void Update()
  13.     {
  14.         if (Input.GetMouseButtonDown(0))
  15.         {
  16.             isCounting = !isCounting;
  17.  
  18.             if (isCounting)
  19.             {
  20.                 if (countCoroutine != null)
  21.                     StopCoroutine(countCoroutine);
  22.  
  23.                 countCoroutine = StartCoroutine(CountCoroutine());
  24.             }
  25.  
  26.             else
  27.             {
  28.                 if (countCoroutine != null)
  29.                 {
  30.                     StopCoroutine(countCoroutine);
  31.                 }
  32.             }
  33.         }
  34.     }
  35.  
  36.     IEnumerator CountCoroutine()
  37.     {
  38.         while (isCounting)
  39.         {
  40.             counter++;
  41.             counterText.text = counter.ToString();
  42.             yield return new WaitForSeconds(0.5f);
  43.         }
  44.     }
  45. }
Tags: Unity
Advertisement
Comments
  • RedBum
    12 days
    # text 0.73 KB | 0 0
    1. Реализуйте счетчик, который каждые 0.5 сек. увеличивается на единицу.
    2. При нажатии на кнопку мыши счетчик начинает увеличиваться, при повторном нажатии останавливается.
    3. Значения счетчика не обнуляются, каждый раз продолжается со значения, на котором остановился.
    4. Для отображения значений счетчика используйте Debug.Log или можете использовать элемент UI, а именно Text.
    5.  
    6. Для решения задачи используйте корутину.
Add Comment
Please, Sign In to add comment
Advertisement