RenamePopup.cs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. using UnityEditor;
  2. using UnityEngine;
  3. namespace XNodeEditor {
  4. /// <summary> Utility for renaming assets </summary>
  5. public class RenamePopup : EditorWindow {
  6. public static RenamePopup current { get; private set; }
  7. public Object target;
  8. public string input;
  9. private bool firstFrame = true;
  10. /// <summary> Show a rename popup for an asset at mouse position. Will trigger reimport of the asset on apply.
  11. public static RenamePopup Show(Object target, float width = 200) {
  12. RenamePopup window = EditorWindow.GetWindow<RenamePopup>(true, "Rename " + target.name, true);
  13. if (current != null) current.Close();
  14. current = window;
  15. window.target = target;
  16. window.input = target.name;
  17. window.minSize = new Vector2(100, 44);
  18. window.position = new Rect(0, 0, width, 44);
  19. GUI.FocusControl("ClearAllFocus");
  20. window.UpdatePositionToMouse();
  21. return window;
  22. }
  23. private void UpdatePositionToMouse() {
  24. if (Event.current == null) return;
  25. Vector3 mousePoint = GUIUtility.GUIToScreenPoint(Event.current.mousePosition);
  26. Rect pos = position;
  27. pos.x = mousePoint.x - position.width * 0.5f;
  28. pos.y = mousePoint.y - 10;
  29. position = pos;
  30. }
  31. private void OnLostFocus() {
  32. // Make the popup close on lose focus
  33. Close();
  34. }
  35. private void OnGUI() {
  36. if (firstFrame) {
  37. UpdatePositionToMouse();
  38. firstFrame = false;
  39. }
  40. input = EditorGUILayout.TextField(input);
  41. Event e = Event.current;
  42. // If input is empty, revert name to default instead
  43. if (input == null || input.Trim() == "") {
  44. if (GUILayout.Button("Revert to default") || (e.isKey && e.keyCode == KeyCode.Return)) {
  45. target.name = NodeEditorUtilities.NodeDefaultName(target.GetType());
  46. AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(target));
  47. Close();
  48. target.TriggerOnValidate();
  49. }
  50. }
  51. // Rename asset to input text
  52. else {
  53. if (GUILayout.Button("Apply") || (e.isKey && e.keyCode == KeyCode.Return)) {
  54. target.name = input;
  55. AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(target));
  56. Close();
  57. target.TriggerOnValidate();
  58. }
  59. }
  60. }
  61. }
  62. }