Inventory grid migration (one shot) and its output: Inventory.prefab and the HUD and enemy panels of ARPG.unity

InventoryGridMigration.Run, exit 0, four scene panels logged (HUD, enemy, the two prefab instances) beside the prefab: a last child `Cells` holding an InventoryGrid (cell size, padding, orientation, IconTexel, BgTexel, raycastTarget from the prototype), GridLayoutGroup removed (a VerticalLayoutGroup beside the menu Content's ContentSizeFitter), panel.Grid and Interactive set, CargoBackgroundColor from the prototype, prototypes deactivated, an inactive Drag Ghost on the prefab. Deleted in the next commit; it stays in history.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
soul 2026-12-01 05:09:09 +01:00
commit 2e8717f5d9
4 changed files with 544 additions and 85 deletions

View file

@ -0,0 +1,141 @@
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.UI;
// One shot (map IG-S, cut inventory-grid-switch): moves the inventory panels from a GridLayoutGroup over sprite cells to an InventoryGrid.
//
// Unity -batchmode -projectPath <project> -executeMethod InventoryGridMigration.Run -logFile <log>
//
// Over Inventory.prefab and the two scene panels of ARPG.unity (the HUD's and the enemy's; the scene's two instances of the prefab take it
// from the prefab). Per panel it reads the old GridLayoutGroup (on the object the cell prototype lives under: Prototype.Instantiate parents
// cells there) and the prototype's own values, adds a last child `Cells` holding the InventoryGrid, removes the group, deactivates the
// prototype, and on the prefab adds the drag ghost. Four scene panels are logged: the two scene objects and the two prefab instances. It logs every object it changed and exits 0, or 1 on any failure. Deleted in the next
// commit; it stays in history.
public static class InventoryGridMigration
{
private const string PrefabPath = "Assets/Prefabs/UI/Inventory.prefab";
private const string ScenePath = "Assets/Scenes/ARPG.unity";
private const string ShaderPath = "Assets/Shaders/InventoryGrid.shader";
private static int _panels;
private static void Log(string line) => Debug.Log("[InventoryGridMigration] " + line);
public static void Run()
{
try
{
var shader = AssetDatabase.LoadAssetAtPath<Shader>(ShaderPath) ?? throw new InvalidOperationException("No " + ShaderPath);
var root = PrefabUtility.LoadPrefabContents(PrefabPath);
try
{
Migrate(root.GetComponentInChildren<InventoryPanel>(true), shader, true);
PrefabUtility.SaveAsPrefabAsset(root, PrefabPath);
}
finally { PrefabUtility.UnloadPrefabContents(root); }
var scene = EditorSceneManager.OpenScene(ScenePath, OpenSceneMode.Single);
var canvas = scene.GetRootGameObjects().First(o => o.name == "Canvas");
foreach (var path in new[] { "Gameplay/Hud Schematic/Inventory", "Gameplay/Enemy Inventory" })
{
var panel = (canvas.transform.Find(path) ?? throw new InvalidOperationException("No " + path)).GetComponent<InventoryPanel>();
Migrate(panel, shader, false);
}
// The scene's two instances of the prefab take the grid from it; they are listed so the count is four.
foreach (var panel in canvas.GetComponentsInChildren<InventoryPanel>(true).Where(p => PrefabUtility.IsPartOfPrefabInstance(p)))
{
if (!panel.Grid || !panel.DragGhost || !panel.Interactive) throw new InvalidOperationException($"Instance {panel.name} did not take the migration from the prefab.");
_panels++;
Log($"panel {_panels}: prefab instance {Path(panel.transform)} takes Grid {panel.Grid.name}, DragGhost {panel.DragGhost.name}, Interactive {panel.Interactive} from the prefab");
}
EditorSceneManager.MarkSceneDirty(scene);
if (!EditorSceneManager.SaveScene(scene)) throw new InvalidOperationException("The scene did not save.");
Log($"done: {_panels} panels");
if (_panels != 4) throw new InvalidOperationException($"Migrated {_panels} panels, want 4.");
EditorApplication.Exit(0);
}
catch (Exception exception)
{
Debug.LogException(exception);
EditorApplication.Exit(1);
}
}
private static string Path(Transform transform) => string.Join("/", transform.GetComponentsInParent<Transform>(true).Reverse().Select(t => t.name));
private static void Migrate(InventoryPanel panel, Shader shader, bool prefab)
{
var prototype = panel.NodePrototype.GetComponent<InventoryCell>() ?? throw new InvalidOperationException("No cell prototype on " + Path(panel.transform));
var container = panel.NodePrototype.transform.parent;
var layout = container.GetComponent<GridLayoutGroup>() ?? throw new InvalidOperationException("No GridLayoutGroup where the prototype lives: " + Path(container));
var iconMultiplier = prototype.Icon.pixelsPerUnitMultiplier;
var backgroundMultiplier = prototype.Background.pixelsPerUnitMultiplier;
var orientation = layout.startCorner == GridLayoutGroup.Corner.UpperRight ? GridOrientation.UpperRight : GridOrientation.LowerLeft;
var interactive = prototype.PointerClickTrigger != null;
Log($"{(prefab ? "prefab panel" : $"panel {_panels + 1}")}: {Path(panel.transform)}: group on {Path(container)} cell {layout.cellSize} padding {layout.padding.left},{layout.padding.right},{layout.padding.top},{layout.padding.bottom} start corner {layout.startCorner}; prototype icon multiplier {iconMultiplier}, background multiplier {backgroundMultiplier}, raycastTarget {prototype.Background.raycastTarget}, click trigger {interactive}, background colour {prototype.Background.color}");
var cells = NewGrid("Cells", container, shader, iconMultiplier, backgroundMultiplier, prototype.Background.raycastTarget);
var rect = (RectTransform) cells.transform;
rect.anchorMin = Vector2.zero;
rect.anchorMax = Vector2.one;
rect.offsetMin = rect.offsetMax = Vector2.zero;
rect.pivot = ((RectTransform) container).pivot;
rect.SetAsLastSibling();
var so = new SerializedObject(cells);
so.FindProperty("_cellSize").floatValue = layout.cellSize.x;
so.FindProperty("_orientation").enumValueIndex = (int) orientation;
var padding = so.FindProperty("_padding");
padding.FindPropertyRelative("m_Left").intValue = layout.padding.left;
padding.FindPropertyRelative("m_Right").intValue = layout.padding.right;
padding.FindPropertyRelative("m_Top").intValue = layout.padding.top;
padding.FindPropertyRelative("m_Bottom").intValue = layout.padding.bottom;
so.ApplyModifiedPropertiesWithoutUndo();
Log($" added {Path(rect)}: cell size {layout.cellSize.x}, padding {layout.padding.left}/{layout.padding.top}, orientation {orientation}, IconTexel {cells.IconTexel:F5}, BgTexel {cells.BgTexel:F5}");
UnityEngine.Object.DestroyImmediate(layout);
Log($" removed GridLayoutGroup from {Path(container)}");
if (container.GetComponent<ContentSizeFitter>())
{
var vertical = container.gameObject.AddComponent<VerticalLayoutGroup>();
vertical.childAlignment = TextAnchor.MiddleCenter;
vertical.padding = new RectOffset();
vertical.childControlWidth = vertical.childControlHeight = true;
vertical.childForceExpandWidth = vertical.childForceExpandHeight = false;
Log($" added VerticalLayoutGroup (middle centre, control child size, no force expand) to {Path(container)} beside its ContentSizeFitter");
}
panel.Grid = cells;
panel.Interactive = interactive;
panel.CargoBackgroundColor = prototype.Background.color;
panel.NodePrototype.gameObject.SetActive(false);
Log($" panel.Grid = {cells.name}, Interactive = {interactive}, CargoBackgroundColor = {panel.CargoBackgroundColor}; deactivated {Path(panel.NodePrototype.transform)}");
if (prefab)
{
var ghost = NewGrid("Drag Ghost", panel.transform, shader, iconMultiplier, backgroundMultiplier, false);
ghost.color = new Color(1, 1, 1, .5f);
ghost.gameObject.SetActive(false);
panel.DragGhost = ghost;
Log($" added inactive {Path(ghost.transform)} with the same look, raycastTarget off, colour (1,1,1,.5), as panel.DragGhost");
}
EditorUtility.SetDirty(panel);
EditorUtility.SetDirty(cells);
if (!prefab) _panels++;
}
private static InventoryGrid NewGrid(string name, Transform parent, Shader shader, float iconMultiplier, float backgroundMultiplier, bool raycastTarget)
{
var go = new GameObject(name, typeof(RectTransform), typeof(CanvasRenderer)) { layer = LayerMask.NameToLayer("UI") };
go.transform.SetParent(parent, false);
var grid = go.AddComponent<InventoryGrid>();
grid.Shader = shader;
grid.IconTexel = InventoryGrid.TexelOf(66f, iconMultiplier);
grid.BgTexel = InventoryGrid.TexelOf(100f, backgroundMultiplier);
grid.raycastTarget = raycastTarget;
return grid;
}
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 212e5feafdf3bcd4aad99fc039e89ddc