GUIHelper.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. using BestHTTP.Examples.Helpers;
  2. using System;
  3. using System.Collections;
  4. using UnityEngine;
  5. using UnityEngine.UI;
  6. namespace BestHTTP.Examples
  7. {
  8. public static class GUIHelper
  9. {
  10. // https://en.wikipedia.org/wiki/Binary_prefix
  11. private static string[] prefixes = new string[] { " B", " KiB", " MiB", " GiB", " TiB" };
  12. public static string GetBytesStr(double bytes, byte precision)
  13. {
  14. int prefixIdx = 0;
  15. while (bytes >= 1024)
  16. {
  17. bytes = bytes / 1024;
  18. prefixIdx++;
  19. }
  20. return bytes.ToString("F" + precision) + prefixes[prefixIdx];
  21. }
  22. public static void RemoveChildren(RectTransform transform, int maxChildCount)
  23. {
  24. while (transform.childCount > maxChildCount)
  25. {
  26. var child = transform.GetChild(0);
  27. child.SetParent(null);
  28. GameObject.Destroy(child.gameObject);
  29. }
  30. }
  31. public static TextListItem AddText(TextListItem prefab, RectTransform contentRoot, string text, int maxEntries, ScrollRect scrollRect)
  32. {
  33. if (contentRoot == null)
  34. return null;
  35. var listItem = GameObject.Instantiate<TextListItem>(prefab, contentRoot, false);
  36. listItem.SetText(text);
  37. GUIHelper.RemoveChildren(contentRoot, maxEntries);
  38. if (scrollRect != null && scrollRect.isActiveAndEnabled)
  39. scrollRect.StartCoroutine(ScrollToBottom(scrollRect));
  40. return listItem;
  41. }
  42. public static IEnumerator ScrollToBottom(ScrollRect scrollRect)
  43. {
  44. yield return null;
  45. if (scrollRect != null && scrollRect.isActiveAndEnabled)
  46. scrollRect.normalizedPosition = new Vector2(0, 0);
  47. }
  48. }
  49. }