通用类C#Unity的自定义属性抽屉

Sta*_*ell 4 c# generics properties unity-game-engine drawer

我在检查器中显示Serializable泛型类时遇到问题.

Serializable泛型类如下:

using UnityEngine;
using System;
using System.Collections;

[Serializable]
public class GenericClass<T> where T : struct
{
    [SerializeField]
    string _serializedString;

    public string SerializedString
    {
        get { return _serializedString; }
        set { _serializedString = value; }
    }

    ... // Functions using the generic type
}
Run Code Online (Sandbox Code Playgroud)

自定义属性抽屉如下:

using UnityEngine;
using UnityEditor;

[CustomPropertyDrawer(typeof(GenericClass<>))]
public class GenericClassDrawer: PropertyDrawer
{
    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        SerializedProperty stringProperty = property.FindPropertyRelative("SerializedString");

        stringProperty.stringValue = EditorGUI.TextField(position, stringProperty.stringValue);
    }
}
Run Code Online (Sandbox Code Playgroud)

MonoBehaviour我正在使用测试泛型类如下:

using UnityEngine;
using System.Collections;

public class TestClass : MonoBehaviour 
{
    enum BasicEnum
    {
        First,
        Second,
        Third,
        Fourth
    }

    [SerializeField]
    GenericClass<BasicEnum> _editorEnum;
}
Run Code Online (Sandbox Code Playgroud)

使用此当前代码,MonoBehaviour TestClass不会在检查器中显示任何内容.它应该显示一个文本字段.

我相信这是由于该类的通用性质,但我一直无法找到使用带有通用类的自定义属性抽屉的任何人的示例.

我的问题是 - 这可能吗?我在代码中遗漏了哪些文本字段按预期显示?如果当前代码不可能,那么泛型类的属性抽屉是否有任何变通方法?

感谢您的时间!

Smi*_*ver 6

这不起作用,因为Unity当前(4.x/5.0)不会序列化泛型类.序列化泛型的一个技巧是继承它们.例如,在这种情况下,您可以:

[Serializable]
class GenericClassInt: GenericClass<int> { ... }

[Serializable]
class GenericClassFloat: GenericClass<float> { ... }
Run Code Online (Sandbox Code Playgroud)

然后你可以拥有字段的编辑器:

[CustomPropertyDrawer(typeof(GenericClassInt))]
[CustomPropertyDrawer(typeof(GenericClassFloat))]
public class GenericClassDrawer: PropertyDrawer { ... }
Run Code Online (Sandbox Code Playgroud)

这并不像它可能那么优雅,但解决了这个问题.