[当创建新类并将其标记为[System.Serializable]
时,检查员将在MonoBehaviour组件中创建并显示其新对象类型的默认对象的默认对象。
尽管创建自定义PropertyDrawer时,您需要自己创建此默认对象,并将其引用放入SerializedProperty.objectReferenceValue(据我了解)。
但是此字段的类型为UnityEngine.Object,无法在此处分配我的新类。如何克服呢?从UnityEngine.Object继承类没有帮助,因为SerializedProperty.objectReferenceValue仍然为null,即使在其中分配了新创建的对象(实际上是相同类型的对象– UnityEngine.Object)之后。
希望我能正确理解您的问题,摘自the Unity documentation:
using UnityEngine;
public enum IngredientUnit { Spoon, Cup, Bowl, Piece }
// Custom serializable class
[Serializable]
public class Ingredient
{
public string name;
public int amount = 1;
public IngredientUnit unit;
}
public class Recipe : MonoBehaviour
{
public Ingredient potionResult;
public Ingredient[] potionIngredients;
}
[CustomPropertyDrawer(typeof(Ingredient))]
public class IngredientDrawerUIE : PropertyDrawer
{
public override VisualElement CreatePropertyGUI(SerializedProperty property)
{
// Create property container element.
var container = new VisualElement();
// Create property fields.
var amountField = new PropertyField(property.FindPropertyRelative("amount"));
var unitField = new PropertyField(property.FindPropertyRelative("unit"));
var nameField = new PropertyField(property.FindPropertyRelative("name"), "Fancy Name");
// Add fields to the container.
container.Add(amountField);
container.Add(unitField);
container.Add(nameField);
return container;
}
}
因此,当您查看带有Recipe
组件的GameObject时,Unity的检查器将显示以下内容:
因此,您无需继承任何东西,只需将要创建属性抽屉的类标记为Serializable
,并为其创建属性抽屉类(请确保将其放置在Editor
文件夹中,或者创建一个仅在使用程序集定义文件时才针对编辑器的程序集定义文件。