LoadingBar.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. using UnityEngine;
  2. using UnityEngine.Serialization;
  3. using UnityEngine.UI;
  4. namespace ARLocation.UI
  5. {
  6. public class LoadingBar : MonoBehaviour
  7. {
  8. [FormerlySerializedAs("fillPercentage")] [Range(0, 1)]
  9. public float FillPercentage = 0.4f;
  10. [FormerlySerializedAs("startColor")] public Color StartColor = Color.green;
  11. [FormerlySerializedAs("middleColor")] public Color MiddleColor = Color.yellow;
  12. [FormerlySerializedAs("endColor")] public Color EndColor = Color.red;
  13. [FormerlySerializedAs("textColor")] public Color TextColor = Color.blue;
  14. [FormerlySerializedAs("usePercentageText")] public bool UsePercentageText;
  15. [FormerlySerializedAs("text")] public string Text = "100";
  16. private GameObject fillBar;
  17. private Text barText;
  18. private RectTransform rectTransform;
  19. private RectTransform fillBarRect;
  20. private Image fillBarImage;
  21. // Use this for initialization
  22. void Start()
  23. {
  24. fillBar = transform.Find("Bar").gameObject;
  25. barText = transform.Find("Text").gameObject.GetComponent<Text>();
  26. barText.color = TextColor;
  27. barText.fontStyle = FontStyle.Bold;
  28. rectTransform = GetComponent<RectTransform>();
  29. fillBarRect = fillBar.GetComponent<RectTransform>();
  30. fillBarImage = fillBar.GetComponent<Image>();
  31. }
  32. // Update is called once per frame
  33. void Update()
  34. {
  35. var w = rectTransform.rect.width;
  36. fillBarRect.offsetMin = new Vector2(0, 0);
  37. fillBarRect.offsetMax = new Vector2((FillPercentage - 1) * w, 0);
  38. if (FillPercentage < 0.5)
  39. {
  40. fillBarImage.color = Color.Lerp(StartColor, MiddleColor, FillPercentage * 2);
  41. }
  42. else
  43. {
  44. fillBarImage.color = Color.Lerp(MiddleColor, EndColor, (FillPercentage - 0.5f) * 2);
  45. }
  46. if (UsePercentageText)
  47. {
  48. barText.text = ((int)(FillPercentage * 100.0f)) + "%";
  49. }
  50. else
  51. {
  52. barText.text = Text;
  53. }
  54. }
  55. }
  56. }