Advertisement
romi_fauzi

ModulaBar.cs

Apr 20th, 2020
999
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.47 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5.  
  6. public class ModuloBar : MonoBehaviour
  7. {
  8.     [SerializeField] Slider progressBar;
  9.     [SerializeField] Text levelTier;
  10.  
  11.     [SerializeField] int maxTier = 6; //max amount per tier, always set this value to the visual bar + 1
  12.     [SerializeField] int statValue = 0; //your real progress value
  13.  
  14.     [SerializeField] Button addBtn, subBtn;
  15.  
  16.     // Start is called before the first frame update
  17.     void Start()
  18.     {
  19.         UpdateProgressBar();
  20.  
  21.         addBtn.onClick.AddListener(IncreaseProgress);
  22.         subBtn.onClick.AddListener(DecreaseProgress);
  23.     }
  24.  
  25.     //Method for updating the progress bar based on the real progress value (statValue)
  26.     private void UpdateProgressBar()
  27.     {
  28.         progressBar.value = statValue % maxTier; //Increase the bar value using modulo, so it resets when reach the max tier amount
  29.         levelTier.text = Mathf.Floor(statValue / ((float)maxTier)).ToString(); //Use floor operation to define our current tier
  30.     }
  31.  
  32.     //Method for increasing progress
  33.     void IncreaseProgress()
  34.     {
  35.         statValue++;
  36.         UpdateProgressBar();
  37.     }
  38.  
  39.     //Method for decreasing progress, and clamp the value, so it doesn't go below the minimum value (in this case 0)
  40.     void DecreaseProgress()
  41.     {
  42.         statValue--;
  43.         statValue = Mathf.Clamp(statValue, 0, int.MaxValue);
  44.         UpdateProgressBar();
  45.     }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement