GUIHelper.cs 1.8 KB

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