PhotonEditorUtils.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. // ----------------------------------------------------------------------------
  2. // <copyright file="PhotonEditorUtils.cs" company="Exit Games GmbH">
  3. // PhotonNetwork Framework for Unity - Copyright (C) 2018 Exit Games GmbH
  4. // </copyright>
  5. // <summary>
  6. // Unity Editor Utils
  7. // </summary>
  8. // <author>developer@exitgames.com</author>
  9. // ----------------------------------------------------------------------------
  10. #pragma warning disable 618 // Deprecation warnings
  11. #if UNITY_2017_4_OR_NEWER
  12. #define SUPPORTED_UNITY
  13. #endif
  14. #if UNITY_EDITOR
  15. namespace Photon.Realtime
  16. {
  17. using System;
  18. using System.Collections.Generic;
  19. using System.Linq;
  20. using UnityEditor;
  21. using UnityEngine;
  22. using System.IO;
  23. using System.Text;
  24. using UnityEngine.Networking;
  25. [InitializeOnLoad]
  26. public static class PhotonEditorUtils
  27. {
  28. /// <summary>Stores a flag which tells Editor scripts if the PhotonEditor.OnProjectChanged got called since initialization.</summary>
  29. /// <remarks>If not, the AssetDatabase is likely not usable yet and instances of ScriptableObject can't be loaded.</remarks>
  30. public static bool ProjectChangedWasCalled;
  31. /// <summary>True if the ChatClient of the Photon Chat API is available. If so, the editor may (e.g.) show additional options in settings.</summary>
  32. public static bool HasChat;
  33. /// <summary>True if the VoiceClient of the Photon Voice API is available. If so, the editor may (e.g.) show additional options in settings.</summary>
  34. public static bool HasVoice;
  35. /// <summary>True if PUN is in the project.</summary>
  36. public static bool HasPun;
  37. /// <summary>True if Photon Fusion is available in the project (and enabled).</summary>
  38. public static bool HasFusion;
  39. /// <summary>True if the PhotonEditorUtils checked the available products / APIs. If so, the editor may (e.g.) show additional options in settings.</summary>
  40. public static bool HasCheckedProducts;
  41. static PhotonEditorUtils()
  42. {
  43. HasVoice = Type.GetType("Photon.Voice.VoiceClient, Assembly-CSharp") != null || Type.GetType("Photon.Voice.VoiceClient, Assembly-CSharp-firstpass") != null || Type.GetType("Photon.Voice.VoiceClient, PhotonVoice.API") != null;
  44. HasChat = Type.GetType("Photon.Chat.ChatClient, Assembly-CSharp") != null || Type.GetType("Photon.Chat.ChatClient, Assembly-CSharp-firstpass") != null || Type.GetType("Photon.Chat.ChatClient, PhotonChat") != null;
  45. HasPun = Type.GetType("Photon.Pun.PhotonNetwork, Assembly-CSharp") != null || Type.GetType("Photon.Pun.PhotonNetwork, Assembly-CSharp-firstpass") != null || Type.GetType("Photon.Pun.PhotonNetwork, PhotonUnityNetworking") != null;
  46. #if FUSION_WEAVER
  47. HasFusion = true;
  48. #endif
  49. PhotonEditorUtils.HasCheckedProducts = true;
  50. if (EditorPrefs.HasKey("DisablePun") && EditorPrefs.GetBool("DisablePun"))
  51. {
  52. HasPun = false;
  53. }
  54. if (HasPun)
  55. {
  56. // MOUNTING SYMBOLS
  57. #if !PHOTON_UNITY_NETWORKING
  58. AddScriptingDefineSymbolToAllBuildTargetGroups("PHOTON_UNITY_NETWORKING");
  59. #endif
  60. #if !PUN_2_0_OR_NEWER
  61. AddScriptingDefineSymbolToAllBuildTargetGroups("PUN_2_0_OR_NEWER");
  62. #endif
  63. #if !PUN_2_OR_NEWER
  64. AddScriptingDefineSymbolToAllBuildTargetGroups("PUN_2_OR_NEWER");
  65. #endif
  66. #if !PUN_2_19_OR_NEWER
  67. AddScriptingDefineSymbolToAllBuildTargetGroups("PUN_2_19_OR_NEWER");
  68. #endif
  69. }
  70. }
  71. /// <summary>
  72. /// Adds a given scripting define symbol to all build target groups
  73. /// You can see all scripting define symbols ( not the internal ones, only the one for this project), in the PlayerSettings inspector
  74. /// </summary>
  75. /// <param name="defineSymbol">Define symbol.</param>
  76. public static void AddScriptingDefineSymbolToAllBuildTargetGroups(string defineSymbol)
  77. {
  78. foreach (BuildTarget target in Enum.GetValues(typeof(BuildTarget)))
  79. {
  80. BuildTargetGroup group = BuildPipeline.GetBuildTargetGroup(target);
  81. if (group == BuildTargetGroup.Unknown)
  82. {
  83. continue;
  84. }
  85. var defineSymbols = PlayerSettings.GetScriptingDefineSymbolsForGroup(group).Split(';').Select(d => d.Trim()).ToList();
  86. if (!defineSymbols.Contains(defineSymbol))
  87. {
  88. defineSymbols.Add(defineSymbol);
  89. try
  90. {
  91. PlayerSettings.SetScriptingDefineSymbolsForGroup(group, string.Join(";", defineSymbols.ToArray()));
  92. }
  93. catch (Exception e)
  94. {
  95. Debug.Log("Could not set Photon " + defineSymbol + " defines for build target: " + target + " group: " + group + " " + e);
  96. }
  97. }
  98. }
  99. }
  100. /// <summary>
  101. /// Removes PUN2's Script Define Symbols from project
  102. /// </summary>
  103. public static void CleanUpPunDefineSymbols()
  104. {
  105. foreach (BuildTarget target in Enum.GetValues(typeof(BuildTarget)))
  106. {
  107. BuildTargetGroup group = BuildPipeline.GetBuildTargetGroup(target);
  108. if (group == BuildTargetGroup.Unknown)
  109. {
  110. continue;
  111. }
  112. var defineSymbols = PlayerSettings.GetScriptingDefineSymbolsForGroup(group)
  113. .Split(';')
  114. .Select(d => d.Trim())
  115. .ToList();
  116. List<string> newDefineSymbols = new List<string>();
  117. foreach (var symbol in defineSymbols)
  118. {
  119. if ("PHOTON_UNITY_NETWORKING".Equals(symbol) || symbol.StartsWith("PUN_2_"))
  120. {
  121. continue;
  122. }
  123. newDefineSymbols.Add(symbol);
  124. }
  125. try
  126. {
  127. PlayerSettings.SetScriptingDefineSymbolsForGroup(group, string.Join(";", newDefineSymbols.ToArray()));
  128. }
  129. catch (Exception e)
  130. {
  131. Debug.LogErrorFormat("Could not set clean up PUN2's define symbols for build target: {0} group: {1}, {2}", target, group, e);
  132. }
  133. }
  134. }
  135. /// <summary>
  136. /// Gets the parent directory of a path. Recursive Function, will return null if parentName not found
  137. /// </summary>
  138. /// <returns>The parent directory</returns>
  139. /// <param name="path">Path.</param>
  140. /// <param name="parentName">Parent name.</param>
  141. public static string GetParent(string path, string parentName)
  142. {
  143. var dir = new DirectoryInfo(path);
  144. if (dir.Parent == null)
  145. {
  146. return null;
  147. }
  148. if (string.IsNullOrEmpty(parentName))
  149. {
  150. return dir.Parent.FullName;
  151. }
  152. if (dir.Parent.Name == parentName)
  153. {
  154. return dir.Parent.FullName;
  155. }
  156. return GetParent(dir.Parent.FullName, parentName);
  157. }
  158. /// <summary>
  159. /// Check if a GameObject is a prefab asset or part of a prefab asset, as opposed to an instance in the scene hierarchy
  160. /// </summary>
  161. /// <returns><c>true</c>, if a prefab asset or part of it, <c>false</c> otherwise.</returns>
  162. /// <param name="go">The GameObject to check</param>
  163. public static bool IsPrefab(GameObject go)
  164. {
  165. #if UNITY_2021_2_OR_NEWER
  166. return UnityEditor.SceneManagement.PrefabStageUtility.GetPrefabStage(go) != null || EditorUtility.IsPersistent(go);
  167. #elif UNITY_2018_3_OR_NEWER
  168. return UnityEditor.Experimental.SceneManagement.PrefabStageUtility.GetPrefabStage(go) != null || EditorUtility.IsPersistent(go);
  169. #else
  170. return EditorUtility.IsPersistent(go);
  171. #endif
  172. }
  173. //https://forum.unity.com/threads/using-unitywebrequest-in-editor-tools.397466/#post-4485181
  174. public static void StartCoroutine(System.Collections.IEnumerator update)
  175. {
  176. EditorApplication.CallbackFunction closureCallback = null;
  177. closureCallback = () =>
  178. {
  179. try
  180. {
  181. if (update.MoveNext() == false)
  182. {
  183. EditorApplication.update -= closureCallback;
  184. }
  185. }
  186. catch (Exception ex)
  187. {
  188. Debug.LogException(ex);
  189. EditorApplication.update -= closureCallback;
  190. }
  191. };
  192. EditorApplication.update += closureCallback;
  193. }
  194. public static System.Collections.IEnumerator HttpPost(string url, Dictionary<string, string> headers, byte[] payload, Action<string> successCallback, Action<string> errorCallback)
  195. {
  196. using (UnityWebRequest w = new UnityWebRequest(url, "POST"))
  197. {
  198. if (payload != null)
  199. {
  200. w.uploadHandler = new UploadHandlerRaw(payload);
  201. }
  202. w.downloadHandler = new DownloadHandlerBuffer();
  203. if (headers != null)
  204. {
  205. foreach (var header in headers)
  206. {
  207. w.SetRequestHeader(header.Key, header.Value);
  208. }
  209. }
  210. #if UNITY_2017_2_OR_NEWER
  211. yield return w.SendWebRequest();
  212. #else
  213. yield return w.Send();
  214. #endif
  215. while (w.isDone == false)
  216. yield return null;
  217. #if UNITY_2020_2_OR_NEWER
  218. if (w.result == UnityWebRequest.Result.ProtocolError || w.result == UnityWebRequest.Result.ConnectionError || w.result == UnityWebRequest.Result.DataProcessingError)
  219. #elif UNITY_2017_1_OR_NEWER
  220. if (w.isNetworkError || w.isHttpError)
  221. #endif
  222. {
  223. if (errorCallback != null)
  224. {
  225. errorCallback(w.error);
  226. }
  227. }
  228. else
  229. {
  230. if (successCallback != null)
  231. {
  232. successCallback(w.downloadHandler.text);
  233. }
  234. }
  235. }
  236. }
  237. /// <summary>
  238. /// Creates a Foldout using a toggle with (GUIStyle)"Foldout") and a separate label. This is a workaround for 2019.3 foldout arrows not working.
  239. /// </summary>
  240. /// <param name="isExpanded"></param>
  241. /// <param name="label"></param>
  242. /// <returns>Returns the new isExpanded value.</returns>
  243. public static bool Foldout(this SerializedProperty isExpanded, GUIContent label)
  244. {
  245. var rect = EditorGUILayout.GetControlRect();
  246. bool newvalue = EditorGUI.Toggle(new Rect(rect) { xMin = rect.xMin + 2 }, GUIContent.none, isExpanded.boolValue, (GUIStyle)"Foldout");
  247. EditorGUI.LabelField(new Rect(rect) { xMin = rect.xMin + 15 }, label);
  248. if (newvalue != isExpanded.boolValue)
  249. {
  250. isExpanded.boolValue = newvalue;
  251. isExpanded.serializedObject.ApplyModifiedProperties();
  252. }
  253. return newvalue;
  254. }
  255. /// <summary>
  256. /// Creates a Foldout using a toggle with (GUIStyle)"Foldout") and a separate label. This is a workaround for 2019.3 foldout arrows not working.
  257. /// </summary>
  258. /// <param name="isExpanded"></param>
  259. /// <param name="label"></param>
  260. /// <returns>Returns the new isExpanded value.</returns>
  261. public static bool Foldout(this bool isExpanded, GUIContent label)
  262. {
  263. var rect = EditorGUILayout.GetControlRect();
  264. bool newvalue = EditorGUI.Toggle(new Rect(rect) { xMin = rect.xMin + 2 }, GUIContent.none, isExpanded, (GUIStyle)"Foldout");
  265. EditorGUI.LabelField(new Rect(rect) { xMin = rect.xMin + 15 }, label);
  266. return newvalue;
  267. }
  268. }
  269. public class CleanUpDefinesOnPunDelete : UnityEditor.AssetModificationProcessor
  270. {
  271. public static AssetDeleteResult OnWillDeleteAsset(string assetPath, RemoveAssetOptions rao)
  272. {
  273. if ("Assets/Photon/PhotonUnityNetworking".Equals(assetPath))
  274. {
  275. PhotonEditorUtils.CleanUpPunDefineSymbols();
  276. }
  277. return AssetDeleteResult.DidNotDelete;
  278. }
  279. }
  280. }
  281. #endif