【发布时间】:2018-03-27 00:35:47
【问题描述】:
我正在尝试为 PlayerInventory 类创建自定义检查器。 PlayerInventory 类由项目列表(ScriptableObjects)以及每个项目的数量组成,如下所示:
public class Item : ScriptableObject
{
public string description;
public Sprite picture;
}
public class InventoryItem : ScriptableObject
{
// A reference to the Item object that contains the item's description,
// picture, stats, etc.
public Item item;
// The quantity of this item that the player has in his inventory
public int quantity;
}
[CreateAssetMenu(menuName = "Player/Player Inventory")]
public class PlayerInventory : ScriptableObject
{
// The list of each distinct item that the player has in his inventory,
// along with the quantity of each item
public List<InventoryItem> items;
}
我创建了一个PlayerInventory 的实例作为游戏资产。默认情况下,检查器显示InventoryItems 的列表。但是,我想要检查器显示每个 InventoryItem 元素,其中包含一个字段以为其选择 Item、一个字段用于输入数量和一个“删除”按钮。
下面是我想要实现的目标的可视化示例,以及下面我当前的代码。这个屏幕截图的问题是 Unity 让我为每个元素选择一个 InventoryItem 对象。我希望能够为每个元素选择一个 Item 对象。我遇到的第二个问题是我不知道如何将EditorGUILayout.TextField 设置为InventoryItem.quantity 属性,因为我不知道如何将SerializedProperty 转换为InventoryItem 对象。
[CustomEditor(typeof(PlayerInventory))]
public class PlayerInventoryEditor : Editor
{
public override void OnInspectorGUI()
{
this.serializedObject.Update();
SerializedProperty items = this.serializedObject.FindProperty("items");
for (int i = 0; i < items.arraySize; i++)
{
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Item", GUILayout.Width(50));
// I don't know how to make this line reference the child "item"
// field of the current InventoryItem
EditorGUILayout.PropertyField(items.GetArrayElementAtIndex(i), GUIContent.none, GUILayout.Width(170));
EditorGUILayout.LabelField(" Quantity", GUILayout.Width(80));
// I don't know how to set the text field to the "quantity" field
// of the current InventoryItem
EditorGUILayout.TextField("0", GUILayout.Width(50));
EditorGUILayout.LabelField("", GUILayout.Width(20));
GUILayout.Button("Delete Item");
EditorGUILayout.EndHorizontal();
}
GUILayout.Button("Add Item");
}
}
【问题讨论】:
-
我尝试让
InventoryItem现在继承自ScriptableObject,现在 Inspector 可以像我期望的那样工作,并让我显示item字段。ScriptableObject是什么导致检查员的工作方式不同?