源战役客户端
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

74 lines
2.6 KiB

  1. using System.IO;
  2. using UnityEngine;
  3. using UnityEditor;
  4. using UnityEditor.MemoryProfiler;
  5. public static class PackedMemorySnapshotUtility
  6. {
  7. public static void SaveToFile(PackedMemorySnapshot snapshot)
  8. {
  9. var filePath = EditorUtility.SaveFilePanel("Save Snapshot", null, "MemorySnapshot", "memsnap2");
  10. if(string.IsNullOrEmpty(filePath))
  11. return;
  12. SaveToFile(filePath, snapshot);
  13. }
  14. static void SaveToFile(string filePath, PackedMemorySnapshot snapshot)
  15. {
  16. // Saving snapshots using JsonUtility, instead of BinaryFormatter, is significantly faster.
  17. // I cancelled saving a memory snapshot that is saving using BinaryFormatter after 24 hours.
  18. // Saving the same memory snapshot using JsonUtility.ToJson took 20 seconds only.
  19. UnityEngine.Profiling.Profiler.BeginSample("PackedMemorySnapshotUtility.SaveToFile");
  20. var json = JsonUtility.ToJson(snapshot);
  21. File.WriteAllText(filePath, json);
  22. UnityEngine.Profiling.Profiler.EndSample();
  23. }
  24. public static PackedMemorySnapshot LoadFromFile()
  25. {
  26. var filePath = EditorUtility.OpenFilePanelWithFilters("Load Snapshot", null, new[] { "Snapshots", "memsnap2,memsnap" });
  27. if(string.IsNullOrEmpty(filePath))
  28. return null;
  29. return LoadFromFile(filePath);
  30. }
  31. static PackedMemorySnapshot LoadFromFile(string filePath)
  32. {
  33. PackedMemorySnapshot result = null;
  34. string fileExtension = Path.GetExtension(filePath);
  35. if(string.Equals(fileExtension, ".memsnap2", System.StringComparison.OrdinalIgnoreCase))
  36. {
  37. UnityEngine.Profiling.Profiler.BeginSample("PackedMemorySnapshotUtility.LoadFromFile(json)");
  38. var json = File.ReadAllText(filePath);
  39. result = JsonUtility.FromJson<PackedMemorySnapshot>(json);
  40. UnityEngine.Profiling.Profiler.EndSample();
  41. }
  42. else if(string.Equals(fileExtension, ".memsnap", System.StringComparison.OrdinalIgnoreCase))
  43. {
  44. UnityEngine.Profiling.Profiler.BeginSample("PackedMemorySnapshotUtility.LoadFromFile(binary)");
  45. var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
  46. using(Stream stream = File.Open(filePath, FileMode.Open))
  47. {
  48. result = binaryFormatter.Deserialize(stream) as PackedMemorySnapshot;
  49. }
  50. UnityEngine.Profiling.Profiler.EndSample();
  51. }
  52. else
  53. {
  54. Debug.LogErrorFormat("MemoryProfiler: Unrecognized memory snapshot format '{0}'.", filePath);
  55. }
  56. return result;
  57. }
  58. }