Unity自定义Inspector:能否编辑InventorySlot嵌套Item类的Amount字段?
Absolutely! You can definitely create a custom Inspector for your InventorySlot MonoBehaviour to view and modify the Amount field of its Item member. Here's a straightforward, step-by-step guide with code examples tailored to your setup:
First, let’s recap your existing classes for context (adjust if your code has extra properties):
// Item.cs (regular non-MonoBehaviour class) public class Item { public int Amount; // Add other Item properties (like Name, ItemID, etc.) here if needed } // InventorySlot.cs (MonoBehaviour attached to GameObjects) using UnityEngine; public class InventorySlot : MonoBehaviour { public Item slotItem; // Your Item member variable }
To build the custom Inspector, you’ll need an Editor script. Critical note: This script must live inside a folder named Editor (create one in your project if it doesn’t exist) — Unity only processes editor-specific code from this folder.
Here’s the custom Editor code:
// InventorySlotEditor.cs (place this in your project's Editor folder) using UnityEditor; using UnityEngine; [CustomEditor(typeof(InventorySlot))] public class InventorySlotEditor : Editor { public override void OnInspectorGUI() { // Get a reference to the target InventorySlot component InventorySlot targetSlot = (InventorySlot)target; // Optional: Draw the default Inspector fields first (keeps the slotItem reference visible) base.OnInspectorGUI(); // Add spacing and a header for the Item details EditorGUILayout.Space(); EditorGUILayout.LabelField("Item Amount", EditorStyles.boldLabel); // Handle null case to avoid errors if no Item is assigned if (targetSlot.slotItem == null) { EditorGUILayout.HelpBox("No Item assigned to this slot — assign one to edit Amount!", MessageType.Info); } else { // Draw an editable int field for the Amount value targetSlot.slotItem.Amount = EditorGUILayout.IntField("Current Amount", targetSlot.slotItem.Amount); } // Mark the object as dirty to save changes when you exit Play Mode or save assets if (GUI.changed) { EditorUtility.SetDirty(targetSlot); } } }
Quick Tips:
- Null Safety: The check for
slotItem == nullprevents runtime errors when no Item is assigned to the slot. - Default Inspector: If you don’t want to show the original
slotItemreference field, remove thebase.OnInspectorGUI();line. - Read-Only Mode: To make Amount display-only (not editable), replace the assignment line with
EditorGUILayout.IntField("Current Amount", targetSlot.slotItem.Amount);(no left-hand side assignment). - Saving Changes:
EditorUtility.SetDirty(targetSlot)ensures your edits are persisted instead of being lost when you exit Play Mode.
Once you’ve set this up, select any InventorySlot GameObject in your scene or project window — you’ll see the custom Inspector with the editable Amount field (once an Item is assigned to the slot).
内容的提问来源于stack exchange,提问作者Daarwin

