RandomPrefabInspector.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. using UnityEngine;
  2. using UnityEditor;
  3. using System.Linq;
  4. namespace DunGen.Editor
  5. {
  6. [CustomEditor(typeof(RandomPrefab))]
  7. public class RandomPrefabInspector : UnityEditor.Editor
  8. {
  9. #region Labels
  10. private static class Label
  11. {
  12. public static readonly GUIContent ZeroPosition = new GUIContent("Zero Position", "Snaps the spawned prop to this GameObject's position. Otherwise, the prefab's position will be used as an offset.");
  13. public static readonly GUIContent ZeroRotation =new GUIContent("Zero Rotation", "Snaps the spawned prop to this GameObject's rotation. Otherwise, the prefab's rotation will be used as an offset.");
  14. public static readonly GUIContent Props = new GUIContent("Prefab", "Snaps the spawned prop to this GameObject's rotation. Otherwise, the prefab's rotation will be used as an offset.");
  15. }
  16. #endregion
  17. private SerializedProperty zeroPosition;
  18. private SerializedProperty zeroRotation;
  19. private SerializedProperty props;
  20. private void OnEnable()
  21. {
  22. zeroPosition = serializedObject.FindProperty("ZeroPosition");
  23. zeroRotation = serializedObject.FindProperty("ZeroRotation");
  24. props = serializedObject.FindProperty("Props");
  25. }
  26. public override void OnInspectorGUI()
  27. {
  28. serializedObject.Update();
  29. EditorGUILayout.PropertyField(zeroPosition, Label.ZeroPosition);
  30. EditorGUILayout.PropertyField(zeroRotation, Label.ZeroRotation);
  31. EditorGUILayout.Space();
  32. EditorGUILayout.Space();
  33. EditorGUILayout.PropertyField(props, Label.Props);
  34. HandlePropDragAndDrop(GUILayoutUtility.GetLastRect());
  35. serializedObject.ApplyModifiedProperties();
  36. }
  37. private void HandlePropDragAndDrop(Rect dragTargetRect)
  38. {
  39. var evt = Event.current;
  40. if (evt.type == EventType.DragUpdated || evt.type == EventType.DragPerform)
  41. {
  42. var validGameObjects = EditorUtil.GetValidGameObjects(DragAndDrop.objectReferences, false, true);
  43. if (dragTargetRect.Contains(evt.mousePosition) && validGameObjects.Any())
  44. {
  45. DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
  46. if (evt.type == EventType.DragPerform)
  47. {
  48. Undo.RecordObject(target, "Drag Prop Prefab(s)");
  49. DragAndDrop.AcceptDrag();
  50. var randomPrefabComponent = target as RandomPrefab;
  51. foreach (var dragObject in validGameObjects)
  52. randomPrefabComponent.Props.Weights.Add(new GameObjectChance(dragObject));
  53. Undo.FlushUndoRecordObjects();
  54. }
  55. }
  56. }
  57. }
  58. }
  59. }