Files
untitled-game/Assets/Editor/Inventory/InventoryItemEditor.cs

151 lines
3.8 KiB
C#

using UnityEditor;
using UnityEngine;
[CustomEditor(typeof(InventoryItem))]
public class InventoryItemEditor : Editor
{
private InventoryItem item;
private void OnEnable()
{
item = (InventoryItem)target;
}
public override void OnInspectorGUI()
{
DrawDefaultInspector();
GUILayout.Space(10);
GUILayout.Label("Item Shape", EditorStyles.boldLabel);
DrawGrid();
}
private void DrawGrid()
{
float size = 30f;
for (int y = item.gridY - 1; y >= 0; y--)
{
GUILayout.BeginHorizontal();
for (int x = 0; x < item.gridX; x++)
{
bool occupied = item.IsOccupied(x, y);
GUI.backgroundColor = occupied ? Color.yellow : Color.gray;
if (GUILayout.Button("", GUILayout.Width(size), GUILayout.Height(size)))
{
Undo.RecordObject(item, "Toggle Item Cell");
item.SetOccupied(x, y, !occupied);
EditorUtility.SetDirty(item);
}
}
GUILayout.EndHorizontal();
}
GUI.backgroundColor = Color.white;
}
private void OnSceneGUI()
{
SpriteRenderer sr = item.GetComponent<SpriteRenderer>();
if (sr == null || sr.sprite == null)
{
return;
}
Bounds bounds = sr.bounds;
float cellWidth = bounds.size.x / item.gridX;
float cellHeight = bounds.size.y / item.gridY;
Handles.color = Color.cyan;
// Draw cells
for (int x = 0; x < item.gridX; x++)
{
for (int y = 0; y < item.gridY; y++)
{
float left = bounds.min.x + x * cellWidth;
float bottom = bounds.min.y + y * cellHeight;
Rect cell = new Rect(
left,
bottom,
cellWidth,
cellHeight
);
// Draw occupied cells
if (item.IsOccupied(x, y))
{
Handles.DrawSolidRectangleWithOutline(
cell,
new Color(1, 0.8f, 0, 0.35f),
Color.yellow
);
}
// Draw label
Handles.Label(
new Vector3(
left + cellWidth / 2,
bottom + cellHeight / 2,
0),
$"{x},{y}"
);
}
}
// Draw grid lines
Handles.color = Color.cyan;
for (int x = 0; x <= item.gridX; x++)
{
float xPos = bounds.min.x + x * cellWidth;
Handles.DrawLine(
new Vector3(xPos, bounds.min.y),
new Vector3(xPos, bounds.max.y));
}
for (int y = 0; y <= item.gridY; y++)
{
float yPos = bounds.min.y + y * cellHeight;
Handles.DrawLine(
new Vector3(bounds.min.x, yPos),
new Vector3(bounds.max.x, yPos));
}
// Handle clicks
Event e = Event.current;
if (e.type == EventType.MouseDown && e.button == 0)
{
Vector3 mouseWorld = HandleUtility.GUIPointToWorldRay(e.mousePosition).origin;
int x = Mathf.FloorToInt((mouseWorld.x - bounds.min.x) / cellWidth);
int y = Mathf.FloorToInt((mouseWorld.y - bounds.min.y) / cellHeight);
if (x >= 0 && x < item.gridX
&& y >= 0 && y < item.gridY)
{
Undo.RecordObject(item, "Toggle Item Cell");
item.SetOccupied(x, y, !item.IsOccupied(x, y));
EditorUtility.SetDirty(item);
e.Use();
}
}
}
}