MacroProcessor.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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. namespace YooAsset.Editor
  8. {
  9. [InitializeOnLoad]
  10. public class MacroProcessor : AssetPostprocessor
  11. {
  12. static string OnGeneratedCSProject(string path, string content)
  13. {
  14. XmlDocument xmlDoc = new XmlDocument();
  15. xmlDoc.LoadXml(content);
  16. if (IsCSProjectReferenced(xmlDoc.DocumentElement) == false)
  17. return content;
  18. if (ProcessDefineConstants(xmlDoc.DocumentElement) == false)
  19. return content;
  20. // 将修改后的XML结构重新输出为文本
  21. var stringWriter = new StringWriter();
  22. var writerSettings = new XmlWriterSettings();
  23. writerSettings.Indent = true;
  24. var xmlWriter = XmlWriter.Create(stringWriter, writerSettings);
  25. xmlDoc.WriteTo(xmlWriter);
  26. xmlWriter.Flush();
  27. return stringWriter.ToString();
  28. }
  29. /// <summary>
  30. /// 处理宏定义
  31. /// </summary>
  32. private static bool ProcessDefineConstants(XmlElement element)
  33. {
  34. if (element == null)
  35. return false;
  36. bool processed = false;
  37. foreach (XmlNode node in element.ChildNodes)
  38. {
  39. if (node.Name != "PropertyGroup")
  40. continue;
  41. foreach (XmlNode childNode in node.ChildNodes)
  42. {
  43. if (childNode.Name != "DefineConstants")
  44. continue;
  45. string[] defines = childNode.InnerText.Split(';');
  46. HashSet<string> hashSets = new HashSet<string>(defines);
  47. foreach (string yooMacro in MacroDefine.Macros)
  48. {
  49. string tmpMacro = yooMacro.Trim();
  50. if (hashSets.Contains(tmpMacro) == false)
  51. hashSets.Add(tmpMacro);
  52. }
  53. childNode.InnerText = string.Join(";", hashSets.ToArray());
  54. processed = true;
  55. }
  56. }
  57. return processed;
  58. }
  59. /// <summary>
  60. /// 检测工程是否引用了YooAsset
  61. /// </summary>
  62. private static bool IsCSProjectReferenced(XmlElement element)
  63. {
  64. if (element == null)
  65. return false;
  66. foreach (XmlNode node in element.ChildNodes)
  67. {
  68. if (node.Name != "ItemGroup")
  69. continue;
  70. foreach (XmlNode childNode in node.ChildNodes)
  71. {
  72. if (childNode.Name != "Reference" && childNode.Name != "ProjectReference")
  73. continue;
  74. string include = childNode.Attributes["Include"].Value;
  75. if (include.Contains("YooAsset"))
  76. return true;
  77. }
  78. }
  79. return false;
  80. }
  81. }
  82. }