C# 为自定义PropertyDrawer创建新的默认对象

C# 为自定义PropertyDrawer创建新的默认对象,c#,unity3d,unity-editor,C#,Unity3d,Unity Editor,当您创建新类并将其标记为[System.Serializable]时,您的检查器将为MonoBehavior组件中新类类型的属性创建并显示其默认对象 创建自定义PropertyDrawer时,您需要自己创建此默认对象,并将其引用放入SerializedProperty.objectReferenceValue(据我所知) 但此字段的类型为UnityEngine.Object,无法在此处指定我的新类。如何克服它?从UnityEngine.Object继承类没有帮助,因为SerializedProp

当您创建新类并将其标记为
[System.Serializable]
时,您的检查器将为MonoBehavior组件中新类类型的属性创建并显示其默认对象

创建自定义PropertyDrawer时,您需要自己创建此默认对象,并将其引用放入SerializedProperty.objectReferenceValue(据我所知)


但此字段的类型为UnityEngine.Object,无法在此处指定我的新类。如何克服它?从UnityEngine.Object继承类没有帮助,因为SerializedProperty.objectReferenceValue仍然为空,即使在其中分配了新创建的对象(实际上是同一类型的–UnityEngine.Object)。

我希望我正确理解了您的问题,来自:

因此,当您查看带有
配方
组件的游戏对象时,Unity的inspector将显示如下内容:


因此,您不需要继承任何内容,只需将要创建属性抽屉的类标记为可序列化的,并为其创建属性抽屉类即可(请确保将其放置在
编辑器
文件夹中,或者创建一个仅在使用程序集定义文件时才以编辑器为目标的程序集定义文件)。

没错,我误解了Untiy序列化[System.Serializable]对象本身,您实际上不需要手动创建它们并将其放入SerializedProperty.objectReferenceValue。
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;
    }
}