Advertisement
Guest User

Untitled

a guest
Jan 22nd, 2018
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 31.44 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEditor;
  5. using Fabric;
  6. using System.Reflection;
  7. using System.IO;
  8. using System.Linq;
  9.  
  10. public static class EditorHelper
  11. {
  12. /// <summary>
  13. /// Maintains a list of all audio manager events, used in EditorGUILayoutSelectAudioEvent below.
  14. /// </summary>
  15. private static GUIContent[] m_audioManagerEventList = null;
  16.  
  17. /// <summary>
  18. /// Maintains a list of audio events defined in prefabs.
  19. /// </summary>
  20. private static GUIContent[] m_audioPrefabsEventList = null;
  21.  
  22. /// <summary>
  23. /// Maintains a list of audio events defined both in prefabs and in the audio manager.
  24. /// </summary>
  25. private static GUIContent[] m_audioEventList = null;
  26.  
  27. /// <summary>
  28. /// Draw a generalized list of SerializedProperties. This function focuses mainly on the list header.
  29. /// </summary>
  30. /// <param name="arrayProperty">The property representing the array (list).</param>
  31. /// <param name="listName">Display name for the property.</param>
  32. /// <param name="drawItemCallback">A callback function that will draw an individual list item.</param>
  33. /// <param name="initializeNewItemCallback">Optional callback to initialized a new item created when the "add" button is pressed.</param>
  34. /// <param name="extraSpace">Amount of extra space to draw between list items.</param>
  35. /// <returns>True if an item is deleted and iteration needs to stop.</returns>
  36. public static bool DrawList(
  37. SerializedProperty arrayProperty,
  38. string listName,
  39. Func<SerializedProperty, int, bool> drawItemCallback = null,
  40. Action<SerializedProperty> initializeNewItemCallback = null,
  41. Action createNewItemCallback = null,
  42. float extraSpace = 0f,
  43. bool alwaysExpandListItems = true)
  44. {
  45. if (drawItemCallback == null)
  46. {
  47. drawItemCallback = DrawGenericListEntry;
  48. }
  49.  
  50. GUILayout.Space(10f);
  51.  
  52. if (arrayProperty != null)
  53. {
  54. EditorGUILayout.BeginHorizontal();
  55. int arrayCount = arrayProperty.arraySize;
  56. EditorGUILayout.LabelField("", GUILayout.MaxWidth(10f));
  57. arrayProperty.isExpanded = EditorGUILayout.Foldout(arrayProperty.isExpanded, string.Format("{0} ({1})", listName, arrayCount));
  58. if (GUILayout.Button("Add+", (GUIStyle)"sv_label_3", GUILayout.MaxWidth(60)))
  59. {
  60. if (createNewItemCallback != null)
  61. {
  62. createNewItemCallback();
  63. }
  64. else
  65. {
  66. arrayProperty.InsertArrayElementAtIndex(arrayProperty.arraySize);
  67. }
  68. if (initializeNewItemCallback != null)
  69. {
  70. initializeNewItemCallback(arrayProperty);
  71. }
  72.  
  73. EditorUtility.SetDirty(arrayProperty.serializedObject.targetObject);
  74. arrayProperty.serializedObject.ApplyModifiedProperties();
  75. }
  76. EditorGUILayout.EndHorizontal();
  77. if (arrayProperty.isExpanded)
  78. {
  79. for (int i = 0; i < arrayCount; ++i)
  80. {
  81. if (extraSpace > 0f)
  82. {
  83. GUILayout.Space(extraSpace);
  84. }
  85.  
  86. if (drawItemCallback(arrayProperty, i))
  87. {
  88. return true;
  89. }
  90. }
  91. }
  92. }
  93. else
  94. {
  95. EditorGUILayout.HelpBox("arrayProperty is null", MessageType.Error);
  96. }
  97. return false;
  98. }
  99.  
  100. /// <summary>
  101. /// Draws common elements of list entries.
  102. /// </summary>
  103. /// <param name="property">The property representing the list entry to draw.</param>
  104. /// <param name="arrayProperty">The array property that holds this entry.</param>
  105. /// <param name="index">The index of this item in the array.</param>
  106. /// <returns>True if the entry was deleted and any iteration should cease.</returns>
  107. static public bool DrawGenericListEntry(
  108. SerializedProperty arrayProperty,
  109. int index)
  110. {
  111. return DrawGenericListEntry(arrayProperty, index, true);
  112. }
  113.  
  114. static public bool DrawGenericListEntry(
  115. SerializedProperty arrayProperty,
  116. int index,
  117. bool alwaysExpandListItems)
  118. {
  119. SerializedProperty property = arrayProperty.GetArrayElementAtIndex(index);
  120. return DrawGenericListEntry(property, arrayProperty, index,
  121. null, // element type name
  122. (GUIStyle)"AnimationEventBackground", // gui style
  123. 0, // indent level
  124. () => // draw handler
  125. {
  126. if (property.NextVisible(true))
  127. {
  128. int startDepth = property.depth;
  129. while (true)
  130. {
  131. EditorGUILayout.PropertyField(property, true);
  132. if (!property.NextVisible(false) || property.depth < startDepth)
  133. {
  134. break;
  135. }
  136. }
  137. }
  138. },
  139. alwaysExpandListItems);
  140. }
  141.  
  142. /// <summary>
  143. /// Draws common elements of list entries.
  144. /// </summary>
  145. /// <param name="property">The property representing the list entry to draw.</param>
  146. /// <param name="arrayProperty">The array property that holds this entry.</param>
  147. /// <param name="index">The index of this item in the array.</param>
  148. /// <param name="elementTypeName">The name for this type of element, to provide a name for elements without one.</param>
  149. /// <param name="frameStyle">The GUIStyle to use to frame the element.</param>
  150. /// <param name="indentLevel">How much this entry should be indented.</param>
  151. /// <param name="drawInternal">A callback that will draw the non-generic parts of the entry.</param>
  152. /// <returns>True if the entry was deleted and any iteration should cease.</returns>
  153. static public bool DrawGenericListEntry(
  154. SerializedProperty property,
  155. SerializedProperty arrayProperty,
  156. int index,
  157. string elementTypeName,
  158. GUIStyle frameStyle,
  159. int indentLevel,
  160. Action drawInternal,
  161. bool alwaysExpand = true,
  162. float nameWidth = 150f)
  163. {
  164. SerializedProperty nameProp = property.FindPropertyRelative("m_name");
  165.  
  166. GUIStyle nameStyle = new GUIStyle(frameStyle);
  167. nameStyle.normal.textColor = Color.white;
  168. nameStyle.font = ((GUIStyle)"BoldLabel").font;
  169. nameStyle.fontSize = ((GUIStyle)"BoldLabel").fontSize;
  170. nameStyle.fontStyle = ((GUIStyle)"BoldLabel").fontStyle;
  171. nameStyle.alignment = TextAnchor.MiddleLeft;
  172. nameStyle.padding.left = 5;
  173.  
  174. string newElementName = (String.IsNullOrEmpty(elementTypeName) ?
  175. arrayProperty.displayName + "[" + index.ToString() + "]" :
  176. elementTypeName + " " + index.ToString());
  177.  
  178. if (nameProp != null && string.IsNullOrEmpty(nameProp.stringValue))
  179. {
  180. nameProp.stringValue = newElementName;
  181. }
  182.  
  183. GUILayout.BeginHorizontal();
  184. GUILayout.Space((indentLevel - 1) * 10f);
  185. if (nameProp != null)
  186. {
  187. nameProp.stringValue = EditorGUILayout.TextField(nameProp.stringValue, nameStyle, GUILayout.MaxWidth(nameWidth), GUILayout.MaxHeight(EditorGUIUtility.singleLineHeight));
  188. }
  189. else
  190. {
  191. EditorGUILayout.LabelField(newElementName, nameStyle, GUILayout.MaxWidth(nameWidth), GUILayout.MaxHeight(EditorGUIUtility.singleLineHeight));
  192. }
  193.  
  194. GUIStyle listDeleteButtonStyle = new GUIStyle((GUIStyle)"sv_label_6");
  195. listDeleteButtonStyle.active = ((GUIStyle)"sv_label_5").normal;
  196.  
  197. GUILayout.Space(20f);
  198. GUI.enabled = !(index < arrayProperty.arraySize - 1); // Comment this out to go back to the original system...
  199. if (GUILayout.Button("Delete-", listDeleteButtonStyle, GUILayout.MaxWidth(60), GUILayout.MaxHeight(EditorGUIUtility.singleLineHeight)))
  200. {
  201. arrayProperty.DeleteArrayElementAtIndex(index);
  202. arrayProperty.serializedObject.ApplyModifiedProperties();
  203. return true;
  204. }
  205. // Commented out in case we need to bring these back for special / emergency editing in the future...
  206.  
  207. //GUI.enabled = (index > 0);
  208. //if (GUILayout.Button("▲", (GUIStyle)"ButtonLeft", GUILayout.MaxWidth(25), GUILayout.MaxHeight(EditorGUIUtility.singleLineHeight)))
  209. //{
  210. // arrayProperty.MoveArrayElement(index, index - 1);
  211. // return true;
  212. //}
  213. //GUI.enabled = (index < arrayProperty.arraySize - 1);
  214. //if (GUILayout.Button("▼", (GUIStyle)"ButtonRight", GUILayout.MaxWidth(25), GUILayout.MaxHeight(EditorGUIUtility.singleLineHeight)))
  215. //{
  216. // arrayProperty.MoveArrayElement(index, index + 1);
  217. // return true;
  218. //}
  219. GUI.enabled = true;
  220. GUILayout.EndHorizontal();
  221.  
  222. if (!alwaysExpand)
  223. {
  224. property.isExpanded = EditorGUILayout.Foldout(property.isExpanded, newElementName);
  225. }
  226.  
  227. if (property.isExpanded || alwaysExpand)
  228. {
  229. EditorGUILayout.BeginHorizontal();
  230. GUILayout.Space((indentLevel - 1) * 10f);
  231. EditorGUILayout.BeginVertical(frameStyle);
  232.  
  233. if (drawInternal != null)
  234. {
  235. drawInternal();
  236. }
  237.  
  238. EditorGUILayout.EndVertical();
  239. EditorGUILayout.EndHorizontal();
  240. }
  241. return false;
  242. }
  243.  
  244. private static Dictionary<SerializedProperty, int> s_pageNavigationCache = new Dictionary<SerializedProperty, int>();
  245. public static void DrawPageNavigation(SerializedProperty prop, out int startIndex, out int endIndex)
  246. {
  247. EditorGUILayout.BeginHorizontal();
  248. EditorGUILayout.LabelField("Page:", GUILayout.Width(200f));
  249.  
  250. int itemsPerPage = 10;
  251. int maxItemsPageNum = Mathf.CeilToInt((float)prop.arraySize / (float)itemsPerPage);
  252. int pageNum = s_pageNavigationCache.ContainsKey(prop) ? s_pageNavigationCache[prop] : 1;
  253.  
  254. if (GUILayout.Button("Previous 10", GUILayout.Width(80f)))
  255. {
  256. pageNum = Mathf.Max(pageNum - 1, 1);
  257. }
  258. if (GUILayout.Button("Next 10", GUILayout.Width(80f)))
  259. {
  260. pageNum = Mathf.Min(pageNum + 1, maxItemsPageNum);
  261. }
  262.  
  263. pageNum = EditorGUILayout.IntSlider(pageNum, 1, maxItemsPageNum);
  264. s_pageNavigationCache[prop] = pageNum;
  265.  
  266. EditorGUILayout.EndHorizontal();
  267.  
  268. EditorGUILayout.BeginHorizontal();
  269. EditorGUILayout.LabelField("", GUILayout.MaxHeight(5));
  270. EditorGUILayout.EndHorizontal();
  271.  
  272. startIndex = (pageNum - 1) * itemsPerPage;
  273. endIndex = Mathf.Min(pageNum * itemsPerPage, prop.arraySize) - 1;
  274. }
  275.  
  276. [MenuItem("HydrogenHelper/Audio/Reset Event List Cache", false, 410)]
  277. static public void ResetEventListCache()
  278. {
  279. m_audioManagerEventList = null;
  280. m_audioPrefabsEventList = null;
  281. m_audioEventList = null;
  282. }
  283.  
  284. // static public void EditorFillAudioEvent(9 string label, string currentEvent, bool audioManagerListOnly )
  285.  
  286. /// <summary>
  287. /// Moved here since this can be called in a few places
  288. /// </summary>
  289. /// <param name="audioManagerListOnly"></param>
  290. /// <returns></returns>
  291. private static GUIContent[] InitLists(bool audioManagerListOnly)
  292. {
  293. if (m_audioManagerEventList == null)
  294. {
  295. if (!FillAudioManagerEventList())
  296. {
  297. return null;
  298. }
  299. }
  300. if (m_audioPrefabsEventList == null)
  301. {
  302. if (!FillCharacterAudioEventList())
  303. {
  304. return null;
  305. }
  306. }
  307.  
  308. if (m_audioEventList == null)
  309. {
  310. m_audioEventList = new GUIContent[m_audioManagerEventList.Length + m_audioPrefabsEventList.Length];
  311. Array.Copy(m_audioManagerEventList, m_audioEventList, m_audioManagerEventList.Length);
  312. Array.Copy(m_audioPrefabsEventList, 0, m_audioEventList, m_audioManagerEventList.Length, m_audioPrefabsEventList.Length);
  313. }
  314.  
  315. if (audioManagerListOnly)
  316. {
  317. return m_audioManagerEventList;
  318. }
  319.  
  320. return m_audioEventList;
  321. }
  322.  
  323. /// <summary>
  324. /// Similar to EditorGUISelectAudioEvent but used with EditorGUILayout - returns the string back, or String.Empty if index 0 is selected. Used in Animaton Event Key Editor
  325. /// </summary>
  326. /// <param name="inString"></param>
  327. /// <param name="audioManagerListOnly"></param>
  328. /// <param name="displayOptions"></param>
  329. /// <returns>GUIContent[selectedIndex].text</returns>
  330. static public string EditorDropDownAudioEvent( string inString, bool audioManagerListOnly, GUILayoutOption[] displayOptions )
  331. {
  332. GUIContent[] list = InitLists(audioManagerListOnly);
  333.  
  334. int selectedIndex = 0;
  335. for (int i = 0; i < list.Length; i++)
  336. {
  337. if (string.Compare(list[i].text, inString) == 0)
  338. {
  339. selectedIndex = i;
  340. break;
  341. }
  342. }
  343.  
  344. int index = EditorGUILayout.Popup(selectedIndex, list, displayOptions);
  345. return index == 0 ? String.Empty : list[index].text; // Return empty string is selection 0 is made (hardcoded default for this)
  346. }
  347.  
  348. static public void EditorGUISelectAudioEvent( Rect position, string label, string currentEvent, bool audioManagerListOnly, GenericMenu.MenuFunction2 setValueFunc )
  349. {
  350. GUIContent[] list = InitLists(audioManagerListOnly);
  351.  
  352. if ( null == list )
  353. {
  354. return;
  355. }
  356.  
  357. Rect dropdownRect = EditorGUI.PrefixLabel(position, new GUIContent(label));
  358. dropdownRect.xMax -= 15f;
  359. if (GUI.Button(dropdownRect, currentEvent, (GUIStyle)"DropDownButton"))
  360. {
  361. GenericMenu menu = new GenericMenu();
  362. foreach (GUIContent entry in list)
  363. {
  364. string prefix = GetPrefixForAudioEventDropdown(entry.text);
  365. GUIContent content = entry;
  366. if (!string.IsNullOrEmpty(prefix))
  367. {
  368. content = new GUIContent(prefix + entry.text);
  369. }
  370. menu.AddItem(content, entry.text == currentEvent, setValueFunc, entry.text);
  371. }
  372.  
  373. menu.ShowAsContext();
  374. GUI.changed = true;
  375. }
  376. Rect clearRect = new Rect(dropdownRect.xMax, dropdownRect.yMin, 15f, dropdownRect.height);
  377. if (GUI.Button(clearRect, "", (GUIStyle)"SearchCancelButton"))
  378. {
  379. setValueFunc("");
  380. GUI.changed = true;
  381. }
  382. }
  383.  
  384. private static string GetPrefixForAudioEventDropdown(string eventName)
  385. {
  386. if (eventName.StartsWith("fts_sw_"))
  387. {
  388. return "fts_sw_/";
  389. }
  390. else if (eventName.StartsWith("Set_mus_"))
  391. {
  392. return "Set_mus_/";
  393. }
  394. else if (eventName.StartsWith("Set_state_"))
  395. {
  396. return "Set_state_/";
  397. }
  398. else if (eventName.StartsWith("ui_"))
  399. {
  400. return "ui/";
  401. }
  402. else if (eventName.StartsWith("sw_"))
  403. {
  404. return "sw_/";
  405. }
  406. return "";
  407. }
  408.  
  409. public static bool GetAudioManagerEventNames(out string[] eventNames)
  410. {
  411. eventNames = new string[] { };
  412.  
  413. FabricManager manager = Fabric.FabricSpringBoard.GetFabricManagerInEditor();
  414. if (manager == null)
  415. {
  416. GameObject goPrefab = AssetDatabase.LoadAssetAtPath("Assets/Prefabs/Audio/AudioManager.prefab", typeof(GameObject)) as GameObject;
  417. if (goPrefab == null)
  418. {
  419. Debug.LogError("Cannot load audio manager at Assets/Prefabs/Audio/AudioManager.prefab");
  420. return false;
  421. }
  422. manager = goPrefab.GetComponent<FabricManager>();
  423. if (manager == null)
  424. {
  425. Debug.LogError("Audio manager at Assets/Prefabs/Audio/AudioManager.prefab has no FabricManager component.");
  426. return false;
  427. }
  428. }
  429.  
  430. Fabric.EventManager eventManager = manager.gameObject.GetComponent<Fabric.EventManager>();
  431. if (eventManager == null)
  432. {
  433. Debug.LogError("Audio manager EventManager component.");
  434. return false;
  435. }
  436. eventNames = eventManager._eventList.ToArray();
  437. return true;
  438. }
  439.  
  440. static private bool FillAudioManagerEventList()
  441. {
  442. string[] eventNames;
  443. AudioEventDrawer.InitAudioEventCacheReference();
  444.  
  445. if (AudioEventDrawer.s_audioEventsCache == null)
  446. {
  447. bool success = GetAudioManagerEventNames(out eventNames);
  448. if (!success)
  449. {
  450. return false;
  451. }
  452. }
  453. else
  454. {
  455. eventNames = AudioEventDrawer.s_audioEventsCache.m_audioEventManagerEvents;
  456. }
  457. m_audioManagerEventList = new GUIContent[eventNames.Length];
  458. for (int i = 0; i < eventNames.Length; ++i)
  459. {
  460. m_audioManagerEventList[i] = new GUIContent(eventNames[i]);
  461. }
  462.  
  463. //Debug.LogWarning("---- Num Audio Manager Events: " + m_audioManagerEventList.Length);
  464. return true;
  465. }
  466.  
  467. public static bool GetCharacterAudioEventNames(out string[] characterEventNames)
  468. {
  469. List<string> fullEventList = new List<string>();
  470. Queue<string> directories = new Queue<string>(Directory.GetDirectories(Application.dataPath + "/Prefabs/Audio"));
  471. while (directories.Count > 0)
  472. {
  473. string directoryName = directories.Dequeue();
  474. foreach (string subDirectory in Directory.GetDirectories(directoryName))
  475. {
  476. directories.Enqueue(subDirectory);
  477. }
  478. string[] prefabFiles = Directory.GetFiles(directoryName, "*.prefab");
  479. foreach (string filename in prefabFiles)
  480. {
  481. string relativePath = filename.Substring(filename.IndexOf("Assets"));
  482. relativePath.Replace('\\', '/');
  483. UnityEngine.GameObject asset = AssetDatabase.LoadAssetAtPath(relativePath, typeof(UnityEngine.GameObject)) as UnityEngine.GameObject;
  484. Fabric.EventListComponent eventList = asset.GetComponent<Fabric.EventListComponent>();
  485. if (eventList != null)
  486. {
  487. foreach (string eventString in eventList._eventList)
  488. {
  489. fullEventList.Add(eventString);
  490. }
  491. }
  492. }
  493. }
  494. characterEventNames = fullEventList.ToArray();
  495. return true;
  496. }
  497.  
  498. static private bool FillCharacterAudioEventList()
  499. {
  500. string[] characterAudioEventNames;
  501. AudioEventDrawer.InitAudioEventCacheReference();
  502.  
  503. if (AudioEventDrawer.s_audioEventsCache == null)
  504. {
  505. GetCharacterAudioEventNames(out characterAudioEventNames);
  506. }
  507. else
  508. {
  509. characterAudioEventNames = AudioEventDrawer.s_audioEventsCache.m_characterAudioEvents;
  510. }
  511.  
  512. m_audioPrefabsEventList = new GUIContent[characterAudioEventNames.Length];
  513. for (int i = 0; i < characterAudioEventNames.Length; ++i)
  514. {
  515. m_audioPrefabsEventList[i] = new GUIContent(characterAudioEventNames[i]);
  516. }
  517.  
  518. //Debug.LogWarning("---- Num Character Audio Events: " + m_audioPrefabsEventList.Length);
  519. return true;
  520. }
  521.  
  522. static public string RemoveExtension( string originalPath )
  523. {
  524. if (string.IsNullOrEmpty(originalPath))
  525. {
  526. return originalPath;
  527. }
  528.  
  529. int idx = originalPath.LastIndexOf('.');
  530. if (idx == -1)
  531. {
  532. return originalPath;
  533. }
  534.  
  535. return originalPath.Substring(0, idx);
  536. }
  537.  
  538. public static T GetFieldByName<T>(string fieldName, BindingFlags bindingFlags, object obj)
  539. {
  540. FieldInfo fieldInfo = obj.GetType().GetField(fieldName, bindingFlags);
  541.  
  542. if (fieldInfo == null)
  543. return default(T);
  544.  
  545. return (T)fieldInfo.GetValue(obj);
  546. }
  547.  
  548. public static T GetActualFieldFromProperty<T>( SerializedProperty property )
  549. {
  550. return GetFieldByName<T>(property.name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, property.serializedObject.targetObject);
  551. }
  552.  
  553. public static string ResolveRelativeAssetPath( string path )
  554. {
  555. int idx = path.IndexOf("/../");
  556. if (idx <= 0)
  557. {
  558. return path;
  559. }
  560.  
  561. string front = path.Substring(0, idx);
  562.  
  563. int lastSlash = front.LastIndexOf('/');
  564. if (lastSlash < 0)
  565. {
  566. return path;
  567. }
  568.  
  569. front = front.Substring(0, lastSlash);
  570. int lastStart = idx + 3;
  571.  
  572. return ResolveRelativeAssetPath(front + path.Substring(lastStart));
  573. }
  574.  
  575. private static GameWideData s_gwdInstance;
  576. public static GameWideData GetGameWideData()
  577. {
  578. if (s_gwdInstance == null)
  579. {
  580. UnityEngine.Object go = UnityEditor.AssetDatabase.LoadAssetAtPath("Assets/Prefabs/Gameplay/GameWideData.prefab", typeof(GameWideData));
  581. s_gwdInstance = go as GameWideData;
  582. if (s_gwdInstance == null)
  583. {
  584. UnityEngine.Debug.LogError("Failed to load GameWideData from Prefabs/Gameplay/GameWideData.prefab");
  585. }
  586. }
  587. return s_gwdInstance;
  588. }
  589.  
  590. // after syncing from perforce the reference may point to null resource links, add option to reload gamewide data's cached reference
  591. public static void ReInitGameWideDataInstance()
  592. {
  593. s_gwdInstance = null;
  594. UnityEngine.Object go = UnityEditor.AssetDatabase.LoadAssetAtPath("Assets/Prefabs/Gameplay/GameWideData.prefab", typeof(GameWideData));
  595. s_gwdInstance = go as GameWideData;
  596. if (s_gwdInstance == null)
  597. {
  598. UnityEngine.Debug.LogError("Failed to load GameWideData from Prefabs/Gameplay/GameWideData.prefab");
  599. }
  600. //else if (Application.isEditor)
  601. //{
  602. // EditorUtility.SetDirty(go);
  603. // AssetDatabase.ImportAsset("Assets/Prefabs/Gameplay/GameWideData.prefab");
  604. // AssetDatabase.SaveAssets();
  605. // AssetDatabase.ImportAsset("Assets/Prefabs/Gameplay/GameWideData.prefab");
  606. //}
  607. }
  608.  
  609. private static InventoryWideData s_iwdInstance;
  610. public static InventoryWideData GetInventoryWideData()
  611. {
  612. if (s_iwdInstance == null)
  613. {
  614. UnityEngine.Object go = UnityEditor.AssetDatabase.LoadAssetAtPath("Assets/Prefabs/Gameplay/InventoryWideData.prefab", typeof(InventoryWideData));
  615. s_iwdInstance = go as InventoryWideData;
  616. if (s_iwdInstance == null)
  617. {
  618. UnityEngine.Debug.LogError("Failed to load InventoryWideData from Prefabs/Gameplay/InventoryWideData.prefab");
  619. }
  620. }
  621. return s_iwdInstance;
  622. }
  623.  
  624. private static FactionWideData s_fwdInstance;
  625. public static FactionWideData GetFactionWideData()
  626. {
  627. if (s_fwdInstance == null)
  628. {
  629. UnityEngine.Object go = UnityEditor.AssetDatabase.LoadAssetAtPath("Assets/Prefabs/Gameplay/FactionWideData.prefab", typeof(FactionWideData));
  630. s_fwdInstance = go as FactionWideData;
  631. if (s_fwdInstance == null)
  632. {
  633. UnityEngine.Debug.LogError("Failed to load FactionWideData from Prefabs/Gameplay/FactionWideData.prefab");
  634. }
  635. }
  636. return s_fwdInstance;
  637. }
  638.  
  639. /// <summary>
  640. /// Tries to determine whether a serialized property is an array element. This is used for Property Drawers to determine
  641. /// if they need to draw foldouts for the property.
  642. /// </summary>
  643. public static bool IsArrayElement(SerializedProperty prop)
  644. {
  645. return (prop.name == "data" && prop.propertyPath[prop.propertyPath.Length - 1] == ']');
  646. }
  647.  
  648. public static void SetAsProjectViewSelection(UnityEngine.Object obj)
  649. {
  650. Selection.activeObject = obj;
  651. if (obj != null)
  652. {
  653. EditorGUIUtility.PingObject(Selection.activeObject);
  654. }
  655. }
  656.  
  657. public static string EnumDisplayName(this SerializedProperty property)
  658. {
  659. return property.enumDisplayNames[property.enumValueIndex];
  660. }
  661.  
  662. public static Editor DrawInspectorForObject(UnityEngine.Object toInspect, Editor prevEditor = null)
  663. {
  664. var editor = prevEditor != null ? prevEditor : Editor.CreateEditor(toInspect);
  665. bool foldout = true;
  666. EditorGUILayout.InspectorTitlebar(foldout, toInspect);
  667. editor.OnInspectorGUI();
  668. return editor;
  669. }
  670.  
  671. //Populates Serialized property for STRINGS when asset is dragged onto field for custom editors
  672. public static bool HandleDragDropForString(SerializedProperty dragDropProp, string Path = "Resources/")
  673. {
  674. bool handled = false;
  675. if (UnityEngine.Event.current.type == EventType.DragUpdated || UnityEngine.Event.current.type == EventType.DragPerform)
  676. {
  677. if (DragAndDrop.paths.Length > 0 && GUILayoutUtility.GetLastRect().Contains(UnityEngine.Event.current.mousePosition))
  678. {
  679. int resourcesStart = DragAndDrop.paths[0].IndexOf(Path);
  680. if (resourcesStart >= 0)
  681. {
  682. string resourceName = DragAndDrop.paths[0].Substring(resourcesStart + (Path).Length);
  683. resourceName = EditorHelper.RemoveExtension(resourceName);
  684. DragAndDrop.visualMode = DragAndDropVisualMode.Move;
  685.  
  686. if (UnityEngine.Event.current.type == EventType.DragPerform)
  687. {
  688. dragDropProp.stringValue = resourceName;
  689. dragDropProp.serializedObject.ApplyModifiedProperties();
  690. handled = true;
  691. }
  692. UnityEngine.Event.current.Use();
  693. }
  694. }
  695. }
  696. return handled;
  697. }
  698. }
  699.  
  700.  
  701. public class ContextMenuExtensions : MonoBehaviour
  702. {
  703. private delegate bool functionToCall(UnityEngine.Component component);
  704.  
  705. /// <summary>
  706. /// Delegate to call function on a component. Used to move components all the waw up or down.
  707. /// </summary>
  708. /// <param name="inContext"></param>
  709. /// <param name="thisDelegate"></param>
  710. private static void InternalMove(UnityEngine.Object inContext, functionToCall thisDelegate)
  711. {
  712. UnityEngine.Component thisComponent = inContext as UnityEngine.Component;
  713.  
  714. if (thisComponent != null)
  715. {
  716. bool stillMoving = true;
  717. int safteyCounter = 100;
  718.  
  719. while (stillMoving)
  720. {
  721. stillMoving = thisDelegate(thisComponent);
  722. if (--safteyCounter <= 0)
  723. {
  724. Debug.LogError("Possible circular components list or some other weirdness (unless we expect > 100 components) with '" + thisComponent.name + "'");
  725. break;
  726. }
  727. }
  728. }
  729. }
  730.  
  731. /// <summary>
  732. /// Requested by design, move this component all the way to the top
  733. /// </summary>
  734. /// <param name="command"></param>
  735. [MenuItem("CONTEXT/Component/Move this fucker way UP")]
  736. static void MoveToTop(MenuCommand command)
  737. {
  738. InternalMove(command.context, new functionToCall(UnityEditorInternal.ComponentUtility.MoveComponentUp));
  739. }
  740.  
  741. /// <summary>
  742. /// Requested by design, move this component all the way to the bottom
  743. /// </summary>
  744. /// <param name="command"></param>
  745. [MenuItem("CONTEXT/Component/Move this fucker way DOWN")]
  746. static void MoveToBottom(MenuCommand command)
  747. {
  748. InternalMove(command.context, new functionToCall(UnityEditorInternal.ComponentUtility.MoveComponentDown));
  749. }
  750. }
  751.  
  752. public static class EditorStyleHelper
  753. {
  754. static Color color1 = new Color(50 / 255.0f, 40 / 255.0f, 40 / 255.0f);
  755. static Color color2 = new Color(34 / 255.0f, 24 / 255.0f, 24 / 255.0f);
  756.  
  757. static Color color3 = new Color(40 / 255.0f, 50 / 255.0f, 40 / 255.0f);
  758. static Color color4 = new Color(24 / 255.0f, 34 / 255.0f, 24 / 255.0f);
  759.  
  760. static Color color5 = new Color(40 / 255.0f, 40 / 255.0f, 50 / 255.0f);
  761. static Color color6 = new Color(24 / 255.0f, 24 / 255.0f, 34 / 255.0f);
  762.  
  763. static Color color7 = new Color(40 / 255.0f, 40 / 255.0f, 40 / 255.0f);
  764. static Color color8 = new Color(24 / 255.0f, 24 / 255.0f, 24 / 255.0f);
  765.  
  766. static Color color9 = new Color(50 / 255.0f, 50 / 255.0f, 40 / 255.0f);
  767. static Color color10 = new Color(34 / 255.0f, 34 / 255.0f, 24 / 255.0f);
  768.  
  769. static Color color11 = new Color(0.8f, 0.8f, 0.8f);
  770.  
  771. public static GUIStyle redStyle = CreateColorStyle(color1, color2);
  772. public static GUIStyle greenStyle = CreateColorStyle(color3, color4);
  773. public static GUIStyle blueStyle = CreateColorStyle(color5, color6);
  774. public static GUIStyle greyStyle = CreateColorStyle(color7, color8);
  775. public static GUIStyle yellowStyle = CreateColorStyle(color9, color10);
  776. public static GUIStyle titleStyle = CreateStyle(color11, FontStyle.Bold);
  777. public static GUIStyle boldFoldoutStyle = BoldFoldoutStyle();
  778. public static GUIStyle foldoutStyle = (GUIStyle)"Foldout";
  779.  
  780. static GUIStyle CreateColorStyle(Color styleColor1, Color styleColor2)
  781. {
  782. const int texSize = 64;
  783. const float texSizeFloat = 64.0f;
  784. Texture2D tempTexture = new Texture2D(texSize, texSize);
  785. for (int i = 1; i <= texSize; ++i)
  786. {
  787. for (int j = 1; j <= texSize; ++j)
  788. {
  789. float frac = i / texSizeFloat;
  790. if (j > i)
  791. {
  792. frac = j / texSizeFloat;
  793. }
  794. Color tempColor = new Color((styleColor1.r * frac) + (styleColor2.r * (1 - frac)),
  795. (styleColor1.g * frac) + (styleColor2.g * (1 - frac)),
  796. (styleColor1.b * frac) + (styleColor2.b * (1 - frac)));
  797. tempTexture.SetPixel(i - 1, (texSize - j), tempColor);
  798. }
  799. }
  800. tempTexture.wrapMode = TextureWrapMode.Clamp;
  801. tempTexture.Apply();
  802. GUIStyle myStyle = new GUIStyle();
  803. myStyle.normal.background = tempTexture;
  804. return myStyle;
  805. }
  806.  
  807. static GUIStyle CreateStyle(Color color, FontStyle fontStyle = FontStyle.Normal)
  808. {
  809. GUIStyle guiStyle = new GUIStyle();
  810. guiStyle.normal.textColor = new Color(0.8f, 0.8f, 0.8f);
  811. guiStyle.fontStyle = FontStyle.Bold;
  812. return guiStyle;
  813. }
  814.  
  815. public static GUIStyle NormalButtonStyle(int size = 14)
  816. {
  817. return NormalButtonStyle(EditorStyles.miniButton.normal.textColor, size);
  818. }
  819.  
  820. public static GUIStyle NormalButtonStyle(Color textColor, int fontSize = 14)
  821. {
  822. var style = new GUIStyle(EditorStyles.miniButton);
  823. style.fontSize = fontSize;
  824. style.alignment = TextAnchor.MiddleLeft;
  825. style.wordWrap = true;
  826. style.richText = true;
  827. style.normal.textColor = textColor;
  828. return style;
  829. }
  830.  
  831. public static GUIStyle SelectedButtonStyle(int size = 14)
  832. {
  833. return NormalButtonStyle(Color.yellow, size);
  834. }
  835.  
  836. public static GUIStyle NormalLabelStyle(int size = 14)
  837. {
  838. var style = new GUIStyle(EditorStyles.label);
  839. style.fontSize = size;
  840. style.richText = true;
  841. return style;
  842. }
  843.  
  844. public static GUIStyle NormalLabelStyle(Color color, int size = 14)
  845. {
  846. var style = new GUIStyle(EditorStyles.label);
  847. style.normal.textColor = color;
  848. style.fontSize = size;
  849. style.richText = true;
  850. return style;
  851. }
  852.  
  853. public static GUIStyle ToggleStyle()
  854. {
  855. var style = new GUIStyle(EditorStyles.toggle);
  856. style.richText = true;
  857. return style;
  858. }
  859.  
  860. public static GUIStyle BoldFoldoutStyle()
  861. {
  862. GUIStyle style = new GUIStyle((GUIStyle)"Foldout");
  863. style.fontStyle = FontStyle.Bold;
  864.  
  865. return style;
  866. }
  867. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement