Skip to content

Instantly share code, notes, and snippets.

@ryanzec
Last active February 17, 2025 19:47
Show Gist options
  • Save ryanzec/e286d4e0ee1fb6f1bf7a47874610bb05 to your computer and use it in GitHub Desktop.
Save ryanzec/e286d4e0ee1fb6f1bf7a47874610bb05 to your computer and use it in GitHub Desktop.
Unity custom editor from drag and drop to change the size of an area
using ProjectEdg.CoreModule;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Tilemaps;
namespace ProjectEdg.WorldModule {
[ExecuteInEditMode]
public class WorldSectionInitializerEntity : MonoBehaviour {
// other code
public void ForceDrawGizmos() {
_cachedDrawControlledArea = _drawControlledArea;
_drawControlledArea = true;
}
public void RestoreDrawGizmos() {
_drawControlledArea = _cachedDrawControlledArea;
}
// other code
}
}
using ProjectEdg.CoreModule;
using ProjectEdg.EditorTools;
using UnityEditor;
using UnityEngine;
namespace ProjectEdg.WorldModule {
[CustomEditor(typeof(WorldSectionInitializerEntity))]
public class WorldSectionInitializerEntityEditor : FoldoutGroupEditor {
private const float HANDLE_SIZE = 0.2f;
private void OnSceneGUI() {
var worldSectionInitializerEntity = (WorldSectionInitializerEntity)target;
var position = VectorUtility.Floor(worldSectionInitializerEntity.transform.position);
EditorGUI.BeginChangeCheck();
// create a single handle in the top-right corner to manage the size of the world section area
var cornerHandle = position + new Vector3(
worldSectionInitializerEntity.Size.x + (HANDLE_SIZE / 2),
worldSectionInitializerEntity.Size.y + (HANDLE_SIZE / 2),
0f
);
// we need to cache this value to be able to determine if the hot control changed this frame in order to
// detect the click / release of said hot control since Handles.FreeMoveHandle will modify this value during
// the same frame
var hotControlId = GUIUtility.hotControl;
Handles.color = Color.yellow;
var handleControlId = GUIUtility.GetControlID(FocusType.Passive);
var newCornerPosition = Handles.FreeMoveHandle(
handleControlId,
cornerHandle,
HANDLE_SIZE,
Vector3.zero,
Handles.DotHandleCap
);
if (EditorToolsUtility.WasControlClicked(handleControlId, hotControlId)) {
worldSectionInitializerEntity.ForceDrawGizmos();
}
if (EditorToolsUtility.WasControlReleased(handleControlId, hotControlId)) {
worldSectionInitializerEntity.RestoreDrawGizmos();
}
if (EditorGUI.EndChangeCheck()) {
Undo.RecordObject(worldSectionInitializerEntity, "modify world section initializer controlled area size");
var newSize = worldSectionInitializerEntity.Size;
newSize.x = Mathf.FloorToInt(Mathf.Max(1f, (newCornerPosition - position).x));
newSize.y = Mathf.FloorToInt(Mathf.Max(1f, (newCornerPosition - position).y));
worldSectionInitializerEntity.Size = newSize;
EditorUtility.SetDirty(worldSectionInitializerEntity);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment