Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using UnityEngine;
- using UnityEditor;
- using Fabric;
- using System.Reflection;
- using System.IO;
- using System.Linq;
- public static class EditorHelper
- {
- /// <summary>
- /// Maintains a list of all audio manager events, used in EditorGUILayoutSelectAudioEvent below.
- /// </summary>
- private static GUIContent[] m_audioManagerEventList = null;
- /// <summary>
- /// Maintains a list of audio events defined in prefabs.
- /// </summary>
- private static GUIContent[] m_audioPrefabsEventList = null;
- /// <summary>
- /// Maintains a list of audio events defined both in prefabs and in the audio manager.
- /// </summary>
- private static GUIContent[] m_audioEventList = null;
- /// <summary>
- /// Draw a generalized list of SerializedProperties. This function focuses mainly on the list header.
- /// </summary>
- /// <param name="arrayProperty">The property representing the array (list).</param>
- /// <param name="listName">Display name for the property.</param>
- /// <param name="drawItemCallback">A callback function that will draw an individual list item.</param>
- /// <param name="initializeNewItemCallback">Optional callback to initialized a new item created when the "add" button is pressed.</param>
- /// <param name="extraSpace">Amount of extra space to draw between list items.</param>
- /// <returns>True if an item is deleted and iteration needs to stop.</returns>
- public static bool DrawList(
- SerializedProperty arrayProperty,
- string listName,
- Func<SerializedProperty, int, bool> drawItemCallback = null,
- Action<SerializedProperty> initializeNewItemCallback = null,
- Action createNewItemCallback = null,
- float extraSpace = 0f,
- bool alwaysExpandListItems = true)
- {
- if (drawItemCallback == null)
- {
- drawItemCallback = DrawGenericListEntry;
- }
- GUILayout.Space(10f);
- if (arrayProperty != null)
- {
- EditorGUILayout.BeginHorizontal();
- int arrayCount = arrayProperty.arraySize;
- EditorGUILayout.LabelField("", GUILayout.MaxWidth(10f));
- arrayProperty.isExpanded = EditorGUILayout.Foldout(arrayProperty.isExpanded, string.Format("{0} ({1})", listName, arrayCount));
- if (GUILayout.Button("Add+", (GUIStyle)"sv_label_3", GUILayout.MaxWidth(60)))
- {
- if (createNewItemCallback != null)
- {
- createNewItemCallback();
- }
- else
- {
- arrayProperty.InsertArrayElementAtIndex(arrayProperty.arraySize);
- }
- if (initializeNewItemCallback != null)
- {
- initializeNewItemCallback(arrayProperty);
- }
- EditorUtility.SetDirty(arrayProperty.serializedObject.targetObject);
- arrayProperty.serializedObject.ApplyModifiedProperties();
- }
- EditorGUILayout.EndHorizontal();
- if (arrayProperty.isExpanded)
- {
- for (int i = 0; i < arrayCount; ++i)
- {
- if (extraSpace > 0f)
- {
- GUILayout.Space(extraSpace);
- }
- if (drawItemCallback(arrayProperty, i))
- {
- return true;
- }
- }
- }
- }
- else
- {
- EditorGUILayout.HelpBox("arrayProperty is null", MessageType.Error);
- }
- return false;
- }
- /// <summary>
- /// Draws common elements of list entries.
- /// </summary>
- /// <param name="property">The property representing the list entry to draw.</param>
- /// <param name="arrayProperty">The array property that holds this entry.</param>
- /// <param name="index">The index of this item in the array.</param>
- /// <returns>True if the entry was deleted and any iteration should cease.</returns>
- static public bool DrawGenericListEntry(
- SerializedProperty arrayProperty,
- int index)
- {
- return DrawGenericListEntry(arrayProperty, index, true);
- }
- static public bool DrawGenericListEntry(
- SerializedProperty arrayProperty,
- int index,
- bool alwaysExpandListItems)
- {
- SerializedProperty property = arrayProperty.GetArrayElementAtIndex(index);
- return DrawGenericListEntry(property, arrayProperty, index,
- null, // element type name
- (GUIStyle)"AnimationEventBackground", // gui style
- 0, // indent level
- () => // draw handler
- {
- if (property.NextVisible(true))
- {
- int startDepth = property.depth;
- while (true)
- {
- EditorGUILayout.PropertyField(property, true);
- if (!property.NextVisible(false) || property.depth < startDepth)
- {
- break;
- }
- }
- }
- },
- alwaysExpandListItems);
- }
- /// <summary>
- /// Draws common elements of list entries.
- /// </summary>
- /// <param name="property">The property representing the list entry to draw.</param>
- /// <param name="arrayProperty">The array property that holds this entry.</param>
- /// <param name="index">The index of this item in the array.</param>
- /// <param name="elementTypeName">The name for this type of element, to provide a name for elements without one.</param>
- /// <param name="frameStyle">The GUIStyle to use to frame the element.</param>
- /// <param name="indentLevel">How much this entry should be indented.</param>
- /// <param name="drawInternal">A callback that will draw the non-generic parts of the entry.</param>
- /// <returns>True if the entry was deleted and any iteration should cease.</returns>
- static public bool DrawGenericListEntry(
- SerializedProperty property,
- SerializedProperty arrayProperty,
- int index,
- string elementTypeName,
- GUIStyle frameStyle,
- int indentLevel,
- Action drawInternal,
- bool alwaysExpand = true,
- float nameWidth = 150f)
- {
- SerializedProperty nameProp = property.FindPropertyRelative("m_name");
- GUIStyle nameStyle = new GUIStyle(frameStyle);
- nameStyle.normal.textColor = Color.white;
- nameStyle.font = ((GUIStyle)"BoldLabel").font;
- nameStyle.fontSize = ((GUIStyle)"BoldLabel").fontSize;
- nameStyle.fontStyle = ((GUIStyle)"BoldLabel").fontStyle;
- nameStyle.alignment = TextAnchor.MiddleLeft;
- nameStyle.padding.left = 5;
- string newElementName = (String.IsNullOrEmpty(elementTypeName) ?
- arrayProperty.displayName + "[" + index.ToString() + "]" :
- elementTypeName + " " + index.ToString());
- if (nameProp != null && string.IsNullOrEmpty(nameProp.stringValue))
- {
- nameProp.stringValue = newElementName;
- }
- GUILayout.BeginHorizontal();
- GUILayout.Space((indentLevel - 1) * 10f);
- if (nameProp != null)
- {
- nameProp.stringValue = EditorGUILayout.TextField(nameProp.stringValue, nameStyle, GUILayout.MaxWidth(nameWidth), GUILayout.MaxHeight(EditorGUIUtility.singleLineHeight));
- }
- else
- {
- EditorGUILayout.LabelField(newElementName, nameStyle, GUILayout.MaxWidth(nameWidth), GUILayout.MaxHeight(EditorGUIUtility.singleLineHeight));
- }
- GUIStyle listDeleteButtonStyle = new GUIStyle((GUIStyle)"sv_label_6");
- listDeleteButtonStyle.active = ((GUIStyle)"sv_label_5").normal;
- GUILayout.Space(20f);
- GUI.enabled = !(index < arrayProperty.arraySize - 1); // Comment this out to go back to the original system...
- if (GUILayout.Button("Delete-", listDeleteButtonStyle, GUILayout.MaxWidth(60), GUILayout.MaxHeight(EditorGUIUtility.singleLineHeight)))
- {
- arrayProperty.DeleteArrayElementAtIndex(index);
- arrayProperty.serializedObject.ApplyModifiedProperties();
- return true;
- }
- // Commented out in case we need to bring these back for special / emergency editing in the future...
- //GUI.enabled = (index > 0);
- //if (GUILayout.Button("▲", (GUIStyle)"ButtonLeft", GUILayout.MaxWidth(25), GUILayout.MaxHeight(EditorGUIUtility.singleLineHeight)))
- //{
- // arrayProperty.MoveArrayElement(index, index - 1);
- // return true;
- //}
- //GUI.enabled = (index < arrayProperty.arraySize - 1);
- //if (GUILayout.Button("▼", (GUIStyle)"ButtonRight", GUILayout.MaxWidth(25), GUILayout.MaxHeight(EditorGUIUtility.singleLineHeight)))
- //{
- // arrayProperty.MoveArrayElement(index, index + 1);
- // return true;
- //}
- GUI.enabled = true;
- GUILayout.EndHorizontal();
- if (!alwaysExpand)
- {
- property.isExpanded = EditorGUILayout.Foldout(property.isExpanded, newElementName);
- }
- if (property.isExpanded || alwaysExpand)
- {
- EditorGUILayout.BeginHorizontal();
- GUILayout.Space((indentLevel - 1) * 10f);
- EditorGUILayout.BeginVertical(frameStyle);
- if (drawInternal != null)
- {
- drawInternal();
- }
- EditorGUILayout.EndVertical();
- EditorGUILayout.EndHorizontal();
- }
- return false;
- }
- private static Dictionary<SerializedProperty, int> s_pageNavigationCache = new Dictionary<SerializedProperty, int>();
- public static void DrawPageNavigation(SerializedProperty prop, out int startIndex, out int endIndex)
- {
- EditorGUILayout.BeginHorizontal();
- EditorGUILayout.LabelField("Page:", GUILayout.Width(200f));
- int itemsPerPage = 10;
- int maxItemsPageNum = Mathf.CeilToInt((float)prop.arraySize / (float)itemsPerPage);
- int pageNum = s_pageNavigationCache.ContainsKey(prop) ? s_pageNavigationCache[prop] : 1;
- if (GUILayout.Button("Previous 10", GUILayout.Width(80f)))
- {
- pageNum = Mathf.Max(pageNum - 1, 1);
- }
- if (GUILayout.Button("Next 10", GUILayout.Width(80f)))
- {
- pageNum = Mathf.Min(pageNum + 1, maxItemsPageNum);
- }
- pageNum = EditorGUILayout.IntSlider(pageNum, 1, maxItemsPageNum);
- s_pageNavigationCache[prop] = pageNum;
- EditorGUILayout.EndHorizontal();
- EditorGUILayout.BeginHorizontal();
- EditorGUILayout.LabelField("", GUILayout.MaxHeight(5));
- EditorGUILayout.EndHorizontal();
- startIndex = (pageNum - 1) * itemsPerPage;
- endIndex = Mathf.Min(pageNum * itemsPerPage, prop.arraySize) - 1;
- }
- [MenuItem("HydrogenHelper/Audio/Reset Event List Cache", false, 410)]
- static public void ResetEventListCache()
- {
- m_audioManagerEventList = null;
- m_audioPrefabsEventList = null;
- m_audioEventList = null;
- }
- // static public void EditorFillAudioEvent(9 string label, string currentEvent, bool audioManagerListOnly )
- /// <summary>
- /// Moved here since this can be called in a few places
- /// </summary>
- /// <param name="audioManagerListOnly"></param>
- /// <returns></returns>
- private static GUIContent[] InitLists(bool audioManagerListOnly)
- {
- if (m_audioManagerEventList == null)
- {
- if (!FillAudioManagerEventList())
- {
- return null;
- }
- }
- if (m_audioPrefabsEventList == null)
- {
- if (!FillCharacterAudioEventList())
- {
- return null;
- }
- }
- if (m_audioEventList == null)
- {
- m_audioEventList = new GUIContent[m_audioManagerEventList.Length + m_audioPrefabsEventList.Length];
- Array.Copy(m_audioManagerEventList, m_audioEventList, m_audioManagerEventList.Length);
- Array.Copy(m_audioPrefabsEventList, 0, m_audioEventList, m_audioManagerEventList.Length, m_audioPrefabsEventList.Length);
- }
- if (audioManagerListOnly)
- {
- return m_audioManagerEventList;
- }
- return m_audioEventList;
- }
- /// <summary>
- /// 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
- /// </summary>
- /// <param name="inString"></param>
- /// <param name="audioManagerListOnly"></param>
- /// <param name="displayOptions"></param>
- /// <returns>GUIContent[selectedIndex].text</returns>
- static public string EditorDropDownAudioEvent( string inString, bool audioManagerListOnly, GUILayoutOption[] displayOptions )
- {
- GUIContent[] list = InitLists(audioManagerListOnly);
- int selectedIndex = 0;
- for (int i = 0; i < list.Length; i++)
- {
- if (string.Compare(list[i].text, inString) == 0)
- {
- selectedIndex = i;
- break;
- }
- }
- int index = EditorGUILayout.Popup(selectedIndex, list, displayOptions);
- return index == 0 ? String.Empty : list[index].text; // Return empty string is selection 0 is made (hardcoded default for this)
- }
- static public void EditorGUISelectAudioEvent( Rect position, string label, string currentEvent, bool audioManagerListOnly, GenericMenu.MenuFunction2 setValueFunc )
- {
- GUIContent[] list = InitLists(audioManagerListOnly);
- if ( null == list )
- {
- return;
- }
- Rect dropdownRect = EditorGUI.PrefixLabel(position, new GUIContent(label));
- dropdownRect.xMax -= 15f;
- if (GUI.Button(dropdownRect, currentEvent, (GUIStyle)"DropDownButton"))
- {
- GenericMenu menu = new GenericMenu();
- foreach (GUIContent entry in list)
- {
- string prefix = GetPrefixForAudioEventDropdown(entry.text);
- GUIContent content = entry;
- if (!string.IsNullOrEmpty(prefix))
- {
- content = new GUIContent(prefix + entry.text);
- }
- menu.AddItem(content, entry.text == currentEvent, setValueFunc, entry.text);
- }
- menu.ShowAsContext();
- GUI.changed = true;
- }
- Rect clearRect = new Rect(dropdownRect.xMax, dropdownRect.yMin, 15f, dropdownRect.height);
- if (GUI.Button(clearRect, "", (GUIStyle)"SearchCancelButton"))
- {
- setValueFunc("");
- GUI.changed = true;
- }
- }
- private static string GetPrefixForAudioEventDropdown(string eventName)
- {
- if (eventName.StartsWith("fts_sw_"))
- {
- return "fts_sw_/";
- }
- else if (eventName.StartsWith("Set_mus_"))
- {
- return "Set_mus_/";
- }
- else if (eventName.StartsWith("Set_state_"))
- {
- return "Set_state_/";
- }
- else if (eventName.StartsWith("ui_"))
- {
- return "ui/";
- }
- else if (eventName.StartsWith("sw_"))
- {
- return "sw_/";
- }
- return "";
- }
- public static bool GetAudioManagerEventNames(out string[] eventNames)
- {
- eventNames = new string[] { };
- FabricManager manager = Fabric.FabricSpringBoard.GetFabricManagerInEditor();
- if (manager == null)
- {
- GameObject goPrefab = AssetDatabase.LoadAssetAtPath("Assets/Prefabs/Audio/AudioManager.prefab", typeof(GameObject)) as GameObject;
- if (goPrefab == null)
- {
- Debug.LogError("Cannot load audio manager at Assets/Prefabs/Audio/AudioManager.prefab");
- return false;
- }
- manager = goPrefab.GetComponent<FabricManager>();
- if (manager == null)
- {
- Debug.LogError("Audio manager at Assets/Prefabs/Audio/AudioManager.prefab has no FabricManager component.");
- return false;
- }
- }
- Fabric.EventManager eventManager = manager.gameObject.GetComponent<Fabric.EventManager>();
- if (eventManager == null)
- {
- Debug.LogError("Audio manager EventManager component.");
- return false;
- }
- eventNames = eventManager._eventList.ToArray();
- return true;
- }
- static private bool FillAudioManagerEventList()
- {
- string[] eventNames;
- AudioEventDrawer.InitAudioEventCacheReference();
- if (AudioEventDrawer.s_audioEventsCache == null)
- {
- bool success = GetAudioManagerEventNames(out eventNames);
- if (!success)
- {
- return false;
- }
- }
- else
- {
- eventNames = AudioEventDrawer.s_audioEventsCache.m_audioEventManagerEvents;
- }
- m_audioManagerEventList = new GUIContent[eventNames.Length];
- for (int i = 0; i < eventNames.Length; ++i)
- {
- m_audioManagerEventList[i] = new GUIContent(eventNames[i]);
- }
- //Debug.LogWarning("---- Num Audio Manager Events: " + m_audioManagerEventList.Length);
- return true;
- }
- public static bool GetCharacterAudioEventNames(out string[] characterEventNames)
- {
- List<string> fullEventList = new List<string>();
- Queue<string> directories = new Queue<string>(Directory.GetDirectories(Application.dataPath + "/Prefabs/Audio"));
- while (directories.Count > 0)
- {
- string directoryName = directories.Dequeue();
- foreach (string subDirectory in Directory.GetDirectories(directoryName))
- {
- directories.Enqueue(subDirectory);
- }
- string[] prefabFiles = Directory.GetFiles(directoryName, "*.prefab");
- foreach (string filename in prefabFiles)
- {
- string relativePath = filename.Substring(filename.IndexOf("Assets"));
- relativePath.Replace('\\', '/');
- UnityEngine.GameObject asset = AssetDatabase.LoadAssetAtPath(relativePath, typeof(UnityEngine.GameObject)) as UnityEngine.GameObject;
- Fabric.EventListComponent eventList = asset.GetComponent<Fabric.EventListComponent>();
- if (eventList != null)
- {
- foreach (string eventString in eventList._eventList)
- {
- fullEventList.Add(eventString);
- }
- }
- }
- }
- characterEventNames = fullEventList.ToArray();
- return true;
- }
- static private bool FillCharacterAudioEventList()
- {
- string[] characterAudioEventNames;
- AudioEventDrawer.InitAudioEventCacheReference();
- if (AudioEventDrawer.s_audioEventsCache == null)
- {
- GetCharacterAudioEventNames(out characterAudioEventNames);
- }
- else
- {
- characterAudioEventNames = AudioEventDrawer.s_audioEventsCache.m_characterAudioEvents;
- }
- m_audioPrefabsEventList = new GUIContent[characterAudioEventNames.Length];
- for (int i = 0; i < characterAudioEventNames.Length; ++i)
- {
- m_audioPrefabsEventList[i] = new GUIContent(characterAudioEventNames[i]);
- }
- //Debug.LogWarning("---- Num Character Audio Events: " + m_audioPrefabsEventList.Length);
- return true;
- }
- static public string RemoveExtension( string originalPath )
- {
- if (string.IsNullOrEmpty(originalPath))
- {
- return originalPath;
- }
- int idx = originalPath.LastIndexOf('.');
- if (idx == -1)
- {
- return originalPath;
- }
- return originalPath.Substring(0, idx);
- }
- public static T GetFieldByName<T>(string fieldName, BindingFlags bindingFlags, object obj)
- {
- FieldInfo fieldInfo = obj.GetType().GetField(fieldName, bindingFlags);
- if (fieldInfo == null)
- return default(T);
- return (T)fieldInfo.GetValue(obj);
- }
- public static T GetActualFieldFromProperty<T>( SerializedProperty property )
- {
- return GetFieldByName<T>(property.name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, property.serializedObject.targetObject);
- }
- public static string ResolveRelativeAssetPath( string path )
- {
- int idx = path.IndexOf("/../");
- if (idx <= 0)
- {
- return path;
- }
- string front = path.Substring(0, idx);
- int lastSlash = front.LastIndexOf('/');
- if (lastSlash < 0)
- {
- return path;
- }
- front = front.Substring(0, lastSlash);
- int lastStart = idx + 3;
- return ResolveRelativeAssetPath(front + path.Substring(lastStart));
- }
- private static GameWideData s_gwdInstance;
- public static GameWideData GetGameWideData()
- {
- if (s_gwdInstance == null)
- {
- UnityEngine.Object go = UnityEditor.AssetDatabase.LoadAssetAtPath("Assets/Prefabs/Gameplay/GameWideData.prefab", typeof(GameWideData));
- s_gwdInstance = go as GameWideData;
- if (s_gwdInstance == null)
- {
- UnityEngine.Debug.LogError("Failed to load GameWideData from Prefabs/Gameplay/GameWideData.prefab");
- }
- }
- return s_gwdInstance;
- }
- // after syncing from perforce the reference may point to null resource links, add option to reload gamewide data's cached reference
- public static void ReInitGameWideDataInstance()
- {
- s_gwdInstance = null;
- UnityEngine.Object go = UnityEditor.AssetDatabase.LoadAssetAtPath("Assets/Prefabs/Gameplay/GameWideData.prefab", typeof(GameWideData));
- s_gwdInstance = go as GameWideData;
- if (s_gwdInstance == null)
- {
- UnityEngine.Debug.LogError("Failed to load GameWideData from Prefabs/Gameplay/GameWideData.prefab");
- }
- //else if (Application.isEditor)
- //{
- // EditorUtility.SetDirty(go);
- // AssetDatabase.ImportAsset("Assets/Prefabs/Gameplay/GameWideData.prefab");
- // AssetDatabase.SaveAssets();
- // AssetDatabase.ImportAsset("Assets/Prefabs/Gameplay/GameWideData.prefab");
- //}
- }
- private static InventoryWideData s_iwdInstance;
- public static InventoryWideData GetInventoryWideData()
- {
- if (s_iwdInstance == null)
- {
- UnityEngine.Object go = UnityEditor.AssetDatabase.LoadAssetAtPath("Assets/Prefabs/Gameplay/InventoryWideData.prefab", typeof(InventoryWideData));
- s_iwdInstance = go as InventoryWideData;
- if (s_iwdInstance == null)
- {
- UnityEngine.Debug.LogError("Failed to load InventoryWideData from Prefabs/Gameplay/InventoryWideData.prefab");
- }
- }
- return s_iwdInstance;
- }
- private static FactionWideData s_fwdInstance;
- public static FactionWideData GetFactionWideData()
- {
- if (s_fwdInstance == null)
- {
- UnityEngine.Object go = UnityEditor.AssetDatabase.LoadAssetAtPath("Assets/Prefabs/Gameplay/FactionWideData.prefab", typeof(FactionWideData));
- s_fwdInstance = go as FactionWideData;
- if (s_fwdInstance == null)
- {
- UnityEngine.Debug.LogError("Failed to load FactionWideData from Prefabs/Gameplay/FactionWideData.prefab");
- }
- }
- return s_fwdInstance;
- }
- /// <summary>
- /// Tries to determine whether a serialized property is an array element. This is used for Property Drawers to determine
- /// if they need to draw foldouts for the property.
- /// </summary>
- public static bool IsArrayElement(SerializedProperty prop)
- {
- return (prop.name == "data" && prop.propertyPath[prop.propertyPath.Length - 1] == ']');
- }
- public static void SetAsProjectViewSelection(UnityEngine.Object obj)
- {
- Selection.activeObject = obj;
- if (obj != null)
- {
- EditorGUIUtility.PingObject(Selection.activeObject);
- }
- }
- public static string EnumDisplayName(this SerializedProperty property)
- {
- return property.enumDisplayNames[property.enumValueIndex];
- }
- public static Editor DrawInspectorForObject(UnityEngine.Object toInspect, Editor prevEditor = null)
- {
- var editor = prevEditor != null ? prevEditor : Editor.CreateEditor(toInspect);
- bool foldout = true;
- EditorGUILayout.InspectorTitlebar(foldout, toInspect);
- editor.OnInspectorGUI();
- return editor;
- }
- //Populates Serialized property for STRINGS when asset is dragged onto field for custom editors
- public static bool HandleDragDropForString(SerializedProperty dragDropProp, string Path = "Resources/")
- {
- bool handled = false;
- if (UnityEngine.Event.current.type == EventType.DragUpdated || UnityEngine.Event.current.type == EventType.DragPerform)
- {
- if (DragAndDrop.paths.Length > 0 && GUILayoutUtility.GetLastRect().Contains(UnityEngine.Event.current.mousePosition))
- {
- int resourcesStart = DragAndDrop.paths[0].IndexOf(Path);
- if (resourcesStart >= 0)
- {
- string resourceName = DragAndDrop.paths[0].Substring(resourcesStart + (Path).Length);
- resourceName = EditorHelper.RemoveExtension(resourceName);
- DragAndDrop.visualMode = DragAndDropVisualMode.Move;
- if (UnityEngine.Event.current.type == EventType.DragPerform)
- {
- dragDropProp.stringValue = resourceName;
- dragDropProp.serializedObject.ApplyModifiedProperties();
- handled = true;
- }
- UnityEngine.Event.current.Use();
- }
- }
- }
- return handled;
- }
- }
- public class ContextMenuExtensions : MonoBehaviour
- {
- private delegate bool functionToCall(UnityEngine.Component component);
- /// <summary>
- /// Delegate to call function on a component. Used to move components all the waw up or down.
- /// </summary>
- /// <param name="inContext"></param>
- /// <param name="thisDelegate"></param>
- private static void InternalMove(UnityEngine.Object inContext, functionToCall thisDelegate)
- {
- UnityEngine.Component thisComponent = inContext as UnityEngine.Component;
- if (thisComponent != null)
- {
- bool stillMoving = true;
- int safteyCounter = 100;
- while (stillMoving)
- {
- stillMoving = thisDelegate(thisComponent);
- if (--safteyCounter <= 0)
- {
- Debug.LogError("Possible circular components list or some other weirdness (unless we expect > 100 components) with '" + thisComponent.name + "'");
- break;
- }
- }
- }
- }
- /// <summary>
- /// Requested by design, move this component all the way to the top
- /// </summary>
- /// <param name="command"></param>
- [MenuItem("CONTEXT/Component/Move this fucker way UP")]
- static void MoveToTop(MenuCommand command)
- {
- InternalMove(command.context, new functionToCall(UnityEditorInternal.ComponentUtility.MoveComponentUp));
- }
- /// <summary>
- /// Requested by design, move this component all the way to the bottom
- /// </summary>
- /// <param name="command"></param>
- [MenuItem("CONTEXT/Component/Move this fucker way DOWN")]
- static void MoveToBottom(MenuCommand command)
- {
- InternalMove(command.context, new functionToCall(UnityEditorInternal.ComponentUtility.MoveComponentDown));
- }
- }
- public static class EditorStyleHelper
- {
- static Color color1 = new Color(50 / 255.0f, 40 / 255.0f, 40 / 255.0f);
- static Color color2 = new Color(34 / 255.0f, 24 / 255.0f, 24 / 255.0f);
- static Color color3 = new Color(40 / 255.0f, 50 / 255.0f, 40 / 255.0f);
- static Color color4 = new Color(24 / 255.0f, 34 / 255.0f, 24 / 255.0f);
- static Color color5 = new Color(40 / 255.0f, 40 / 255.0f, 50 / 255.0f);
- static Color color6 = new Color(24 / 255.0f, 24 / 255.0f, 34 / 255.0f);
- static Color color7 = new Color(40 / 255.0f, 40 / 255.0f, 40 / 255.0f);
- static Color color8 = new Color(24 / 255.0f, 24 / 255.0f, 24 / 255.0f);
- static Color color9 = new Color(50 / 255.0f, 50 / 255.0f, 40 / 255.0f);
- static Color color10 = new Color(34 / 255.0f, 34 / 255.0f, 24 / 255.0f);
- static Color color11 = new Color(0.8f, 0.8f, 0.8f);
- public static GUIStyle redStyle = CreateColorStyle(color1, color2);
- public static GUIStyle greenStyle = CreateColorStyle(color3, color4);
- public static GUIStyle blueStyle = CreateColorStyle(color5, color6);
- public static GUIStyle greyStyle = CreateColorStyle(color7, color8);
- public static GUIStyle yellowStyle = CreateColorStyle(color9, color10);
- public static GUIStyle titleStyle = CreateStyle(color11, FontStyle.Bold);
- public static GUIStyle boldFoldoutStyle = BoldFoldoutStyle();
- public static GUIStyle foldoutStyle = (GUIStyle)"Foldout";
- static GUIStyle CreateColorStyle(Color styleColor1, Color styleColor2)
- {
- const int texSize = 64;
- const float texSizeFloat = 64.0f;
- Texture2D tempTexture = new Texture2D(texSize, texSize);
- for (int i = 1; i <= texSize; ++i)
- {
- for (int j = 1; j <= texSize; ++j)
- {
- float frac = i / texSizeFloat;
- if (j > i)
- {
- frac = j / texSizeFloat;
- }
- Color tempColor = new Color((styleColor1.r * frac) + (styleColor2.r * (1 - frac)),
- (styleColor1.g * frac) + (styleColor2.g * (1 - frac)),
- (styleColor1.b * frac) + (styleColor2.b * (1 - frac)));
- tempTexture.SetPixel(i - 1, (texSize - j), tempColor);
- }
- }
- tempTexture.wrapMode = TextureWrapMode.Clamp;
- tempTexture.Apply();
- GUIStyle myStyle = new GUIStyle();
- myStyle.normal.background = tempTexture;
- return myStyle;
- }
- static GUIStyle CreateStyle(Color color, FontStyle fontStyle = FontStyle.Normal)
- {
- GUIStyle guiStyle = new GUIStyle();
- guiStyle.normal.textColor = new Color(0.8f, 0.8f, 0.8f);
- guiStyle.fontStyle = FontStyle.Bold;
- return guiStyle;
- }
- public static GUIStyle NormalButtonStyle(int size = 14)
- {
- return NormalButtonStyle(EditorStyles.miniButton.normal.textColor, size);
- }
- public static GUIStyle NormalButtonStyle(Color textColor, int fontSize = 14)
- {
- var style = new GUIStyle(EditorStyles.miniButton);
- style.fontSize = fontSize;
- style.alignment = TextAnchor.MiddleLeft;
- style.wordWrap = true;
- style.richText = true;
- style.normal.textColor = textColor;
- return style;
- }
- public static GUIStyle SelectedButtonStyle(int size = 14)
- {
- return NormalButtonStyle(Color.yellow, size);
- }
- public static GUIStyle NormalLabelStyle(int size = 14)
- {
- var style = new GUIStyle(EditorStyles.label);
- style.fontSize = size;
- style.richText = true;
- return style;
- }
- public static GUIStyle NormalLabelStyle(Color color, int size = 14)
- {
- var style = new GUIStyle(EditorStyles.label);
- style.normal.textColor = color;
- style.fontSize = size;
- style.richText = true;
- return style;
- }
- public static GUIStyle ToggleStyle()
- {
- var style = new GUIStyle(EditorStyles.toggle);
- style.richText = true;
- return style;
- }
- public static GUIStyle BoldFoldoutStyle()
- {
- GUIStyle style = new GUIStyle((GUIStyle)"Foldout");
- style.fontStyle = FontStyle.Bold;
- return style;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement