Utilities.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. using System;
  2. using System.Runtime.Serialization;
  3. using System.Runtime.Serialization.Formatters.Binary;
  4. using System.IO;
  5. using System.Collections;
  6. using System.Collections.Generic;
  7. using UnityEngine;
  8. namespace KairoEngine.Core
  9. {
  10. public static class Utilities
  11. {
  12. public static string RandomString(int length = 8)
  13. {
  14. var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  15. var stringChars = new char[length];
  16. var random = new System.Random();
  17. for (int i = 0; i < stringChars.Length; i++)
  18. {
  19. stringChars[i] = chars[random.Next(chars.Length)];
  20. }
  21. var finalString = new string(stringChars);
  22. return finalString;
  23. }
  24. public static string TimeToString(float time)
  25. {
  26. string t = "";
  27. if(time < 1)
  28. {
  29. int miliseconds = (int)(time * 1000);
  30. return $"{miliseconds} ms";
  31. }
  32. int minutes = (int)time / 60;
  33. int hours = (int)minutes / 60;
  34. minutes = (int)minutes % 60;
  35. int seconds = (int)time % 60;
  36. if(hours > 1) t += hours.ToString() + " hours ";
  37. else if(hours == 1) t += hours.ToString() + " hour ";
  38. if(minutes > 1) t += minutes.ToString() + " minutes ";
  39. else if(minutes == 1) t += minutes.ToString() + " minute ";
  40. if(seconds == 1) t += seconds.ToString() + " second";
  41. else t += seconds.ToString() + " seconds";
  42. return t;
  43. }
  44. public static float Round(float value, int digits = 2)
  45. {
  46. float mult = Mathf.Pow(10.0f, (float)digits);
  47. return Mathf.Round(value * mult) / mult;
  48. }
  49. public static Stream Serialize(System.Object source)
  50. {
  51. IFormatter formater = new BinaryFormatter();
  52. Stream stream = new MemoryStream();
  53. formater.Serialize(stream, source);
  54. return stream;
  55. }
  56. public static T Deserialze<T>(Stream stream)
  57. {
  58. IFormatter formatter = new BinaryFormatter();
  59. stream.Position = 0;
  60. return (T)formatter.Deserialize(stream);
  61. }
  62. public static T Clone<T>(System.Object source)
  63. {
  64. return Deserialze<T>(Serialize(source));
  65. }
  66. public static string FindFileByName(string fileName)
  67. {
  68. string[] res = System.IO.Directory.GetFiles(Application.dataPath + "/../", fileName, System.IO.SearchOption.AllDirectories);
  69. if (res.Length == 0)
  70. {
  71. Debug.LogError("error message ....");
  72. return fileName;
  73. }
  74. string path = res[0].Replace("\\", "/");
  75. return path;
  76. }
  77. }
  78. }