RspGenerator.cs 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. using System.Collections.Generic;
  2. using System.IO;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Xml;
  6. using UnityEditor;
  7. using UnityEngine;
  8. #if YOO_ASSET_EXPERIMENT
  9. namespace YooAsset.Editor.Experiment
  10. {
  11. [InitializeOnLoad]
  12. public class RspGenerator
  13. {
  14. // csc.rsp文件路径
  15. private static string RspFilePath => Path.Combine(Application.dataPath, "csc.rsp");
  16. static RspGenerator()
  17. {
  18. UpdateRspFile(MacroDefine.Macros, null);
  19. }
  20. /// <summary>
  21. /// 更新csc.rsp文件
  22. /// </summary>
  23. private static void UpdateRspFile(List<string> addMacros, List<string> removeMacros)
  24. {
  25. var existingDefines = new HashSet<string>();
  26. var otherLines = new List<string>();
  27. // 1. 读取现有内容
  28. ReadRspFile(existingDefines, otherLines);
  29. // 2. 添加新宏
  30. if (addMacros != null && addMacros.Count > 0)
  31. {
  32. addMacros.ForEach(x =>
  33. {
  34. if (existingDefines.Contains(x) == false)
  35. existingDefines.Add(x);
  36. });
  37. }
  38. // 3. 移除指定宏
  39. if (removeMacros != null && removeMacros.Count > 0)
  40. {
  41. removeMacros.ForEach(x =>
  42. {
  43. existingDefines.Remove(x);
  44. });
  45. }
  46. // 4. 重新生成内容
  47. WriteRspFile(existingDefines, otherLines);
  48. // 5. 刷新AssetDatabase
  49. AssetDatabase.Refresh();
  50. EditorUtility.RequestScriptReload();
  51. }
  52. /// <summary>
  53. /// 读取csc.rsp文件,返回宏定义和其他行
  54. /// </summary>
  55. private static void ReadRspFile(HashSet<string> defines, List<string> others)
  56. {
  57. if (defines == null)
  58. defines = new HashSet<string>();
  59. if (others == null)
  60. others = new List<string>();
  61. if (File.Exists(RspFilePath) == false)
  62. return;
  63. foreach (string line in File.ReadAllLines(RspFilePath))
  64. {
  65. if (line.StartsWith("-define:"))
  66. {
  67. string[] parts = line.Split(new[] { ':' }, 2);
  68. if (parts.Length == 2)
  69. {
  70. defines.Add(parts[1].Trim());
  71. }
  72. }
  73. else
  74. {
  75. others.Add(line);
  76. }
  77. }
  78. }
  79. /// <summary>
  80. /// 重新写入csc.rsp文件
  81. /// </summary>
  82. private static void WriteRspFile(HashSet<string> defines, List<string> others)
  83. {
  84. StringBuilder sb = new StringBuilder();
  85. if (others != null && others.Count > 0)
  86. {
  87. others.ForEach(o => sb.AppendLine(o));
  88. }
  89. if (defines != null && defines.Count > 0)
  90. {
  91. foreach (string define in defines)
  92. {
  93. sb.AppendLine($"-define:{define}");
  94. }
  95. }
  96. File.WriteAllText(RspFilePath, sb.ToString());
  97. }
  98. }
  99. }
  100. #endif