GameCenterBuild.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. #if UNITY_IOS
  2. using System.IO;
  3. using UnityEditor;
  4. using UnityEditor.Build;
  5. using UnityEditor.Callbacks;
  6. using UnityEditor.iOS.Xcode;
  7. namespace TowerDevil.Editor
  8. {
  9. internal static class GameCenterBuild
  10. {
  11. const string Template = "Assets/TowerDevil/Editor/GameCenterLeaderboards.plist";
  12. const string Night = "BestNightRankID", Score = "TotalScoreRankID";
  13. [PostProcessBuild(1001)]
  14. public static void Configure(BuildTarget target, string path)
  15. {
  16. if (target != BuildTarget.iOS) return;
  17. var source = new PlistDocument();
  18. source.ReadFromFile(Template);
  19. string night = ReadId(source.root, Night), score = ReadId(source.root, Score);
  20. if (night == score) throw new BuildFailedException("Game Center requires two distinct leaderboard IDs in " + Template);
  21. string plistPath = Path.Combine(path, "Info.plist");
  22. var info = new PlistDocument();
  23. info.ReadFromFile(plistPath);
  24. info.root.SetString(Night, night);
  25. info.root.SetString(Score, score);
  26. info.WriteToFile(plistPath);
  27. string pbxPath = PBXProject.GetPBXProjectPath(path);
  28. var project = new PBXProject();
  29. project.ReadFromFile(pbxPath);
  30. string app = project.GetUnityMainTargetGuid();
  31. string entitlements = project.GetEntitlementFilePathForTarget(app);
  32. if (string.IsNullOrEmpty(entitlements)) entitlements = "Unity-iPhone.entitlements";
  33. project.AddFrameworkToProject(project.GetUnityFrameworkTargetGuid(), "GameKit.framework", false);
  34. project.WriteToFile(pbxPath);
  35. var capabilities = new ProjectCapabilityManager(pbxPath, entitlements, null, app);
  36. capabilities.AddGameCenter();
  37. capabilities.Entitlements.root.SetBoolean("com.apple.developer.game-center", true);
  38. capabilities.WriteToFile();
  39. }
  40. static string ReadId(PlistElementDict root, string key)
  41. {
  42. if (root.values.TryGetValue(key, out var value) && value is PlistElementString text &&
  43. !string.IsNullOrWhiteSpace(text.value)) return text.value.Trim();
  44. throw new BuildFailedException("Missing Game Center leaderboard ID " + key + " in " + Template);
  45. }
  46. }
  47. }
  48. #endif