c# - unity3d 中用于继承类的 CustomPropertyDrawer

标签 c# inheritance unity3d

我正在尝试做一些我认为相对简单的事情,但也许我离题太远了。我不知道。我有一个继承自 ScriptableObject 的类,如下所示:

using UnityEngine;
class Automobile : ScriptableObject {
    [SerializedField]
    private int _baseCost = 0;
    public int BaseCost { get { return _baseCost;} set {_baseCost = value;} }
    // More fields and logic
    void OnValidate() {
        BaseCost = _baseCost;
    }
}

然后我有一个继承自 Automobile 的类,如下所示:

public class Car : Automobile {
}

这个类实际上是空的,稍后可能会添加逻辑,现在我只是将 Cars 与 Trucks、Motorcycles 分开,谁知道我还会想出什么。我用了这个script从 unity wiki 为不同的汽车创建一堆 Assets 文件。所有都位于\resources\cars 文件夹下,因此我可以在运行时加载它们

然后我有一个玩家类,其中包含一系列汽车(和卡车,但为简洁起见,我排除了所有这些)

using UnityEngine;
public class Player : MonoBehaviour {
    [SerializeField]
    private Car[] _cars;

    public Car[] Cars { get { return _cars; } set { _cars = value; } }

    void Start () {
        // Load all cars into array
        Cars = Resources.LoadAll<Car>("Cars")
    }
}

为了结束这一切,并实际解释我遇到的问题,我想为从 Automobile 类派生的每个对象创建一个自定义属性抽屉。所以我在编辑器文件夹中创建了一个脚本,如下所示:

using UnityEditor;
using UnityEngine;
[CustomPropertyDrawer(typeof(Automobile), true)]    
public class AutomobileDrawer : PropertyDrawer {
    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) {
        EditorGUI.BeginProperty(position, label, property);
        position = EditorGUI.PrefixLabel(position, GUIUtility.GetControlID(FocusType.Passive), label);

        var indent = EditorGUI.indentLevel;
        EditorGUI.indentLevel = 0;

        Rect BaseCLabel = new Rect(position.x, position.y, 200, position.height);
        Rect BaseC = new Rect(position.x + 35, position.y, 15, position.height);

        EditorGUI.LabelField(BaseVLabel, "Base Cost");

        // This is my error line
        EditorGUI.PropertyField(BaseV, property.FindPropertyRelative("_baseCost"),GUIContent.none);  

        EditorGUI.indentLevel = indent;
        EditorGUI.EndProperty();

        //base.OnGUI(position, property, label);
}

我面临的问题是 FindPropertyRelative 总是返回 null。我几乎 100% 有信心,由于继承水平,我需要建立一条路径(当我转向卡车时会出现问题,因为路径很可能会有所不同),但我不知道它应该是什么是。有什么建议么?

编辑:我忘了提到 Automobile 类使用 OnValidate 函数。我将它添加到代码中。

最佳答案

问题似乎是从 ScriptableObject 继承的类似乎不能很好地与 propertydrawers 一起工作。通过从我的 Automobiles 类中删除继承,并简单地将 [Serializable] 属性应用于类声明,我能够使 propertydrawer 正常工作。

我希望我对此是错误的,因为我需要保留一些继承自 ScriptableObject 的类,希望有人会看到并纠正我,但在那之前,这是我的解决方案。

关于c# - unity3d 中用于继承类的 CustomPropertyDrawer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25072402/

相关文章:

python - 直接调用时返回值的实例(不是实例)

python - 如何继承 python 生成器并覆盖 __iter__

c# - 处理动画工具数据存储的最有效/最快速的方法

c# - .net 如何从 MVC Controller 调用 web api 操作

c# - Try/Catch——我怎么知道在奇怪/复杂的情况下要捕捉什么?

c# - 如何从 C# 字典创建 JSON(类似于 PHP)

具有泛型参数基础的 Java 泛型参数

c# - 属性与字段 : Need help grasping the uses of Properties over Fields

c# - 如何在运行时更改补间动画的 endValueString?

c# - 在Unity3D中显示一个对象几毫秒