ProfileManager.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Collections.ObjectModel;
  4. #if UNITY_EDITOR
  5. using System.Security.Cryptography;
  6. using System.Text;
  7. #endif
  8. using UnityEngine;
  9. //Profile数据管理,一般是一些String数据,通过ClientPrefs进行本地保存
  10. public class ProfileManager
  11. {
  12. public const string AuthProfileCommandLineArg = "-AuthProfile";
  13. string m_Profile;
  14. public string Profile
  15. {
  16. get
  17. {
  18. return m_Profile ??= GetProfile();
  19. }
  20. set
  21. {
  22. m_Profile = value;
  23. onProfileChanged?.Invoke();
  24. }
  25. }
  26. public event Action onProfileChanged;
  27. List<string> m_AvailableProfiles;
  28. public ReadOnlyCollection<string> AvailableProfiles
  29. {
  30. get
  31. {
  32. if(m_AvailableProfiles == null)
  33. {
  34. LoadProfiles();
  35. }
  36. return m_AvailableProfiles.AsReadOnly();
  37. }
  38. }
  39. public void CreateProfile(string profile)
  40. {
  41. m_AvailableProfiles.Add(profile);
  42. SaveProfiles();
  43. }
  44. public void DeleteProfile(string profile)
  45. {
  46. m_AvailableProfiles.Remove(profile);
  47. SaveProfiles();
  48. }
  49. static string GetProfile()
  50. {
  51. var arguments = Environment.GetCommandLineArgs();
  52. for(int i = 0;i < arguments.Length;i++)
  53. {
  54. if(arguments[i] == AuthProfileCommandLineArg)
  55. {
  56. var profileId = arguments[i + 1];
  57. return profileId;
  58. }
  59. }
  60. #if UNITY_EDITOR
  61. var hashedBytes = new MD5CryptoServiceProvider().ComputeHash(Encoding.UTF8.GetBytes(Application.dataPath));
  62. Array.Resize(ref hashedBytes, 16);
  63. return new Guid(hashedBytes).ToString("N");
  64. #else
  65. return "";
  66. #endif
  67. }
  68. void LoadProfiles()
  69. {
  70. m_AvailableProfiles = new List<string>();
  71. var loadedProfiles = ClientPrefs.GetAvailableProfiles();
  72. foreach(var profile in loadedProfiles.Split(','))
  73. {
  74. if(profile.Length > 0)
  75. {
  76. m_AvailableProfiles.Add(profile);
  77. }
  78. }
  79. }
  80. void SaveProfiles()
  81. {
  82. var profilesToSave = "";
  83. foreach(var profile in m_AvailableProfiles)
  84. {
  85. profilesToSave += profile + ",";
  86. }
  87. ClientPrefs.SetAvailableProfiles(profilesToSave);
  88. }
  89. }