微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我在检查器中显示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
}

自定义属性抽屉如下:

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);
    }
}

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

using UnityEngine;
using System.Collections;

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

    [Serializefield]
    Genericclass<BasicEnum> _editorEnum;
}

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

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

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

感谢您的时间!

解决方法:

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

[Serializable]
class GenericclassInt: Genericclass<int> { ... }

[Serializable]
class GenericclassFloat: Genericclass<float> { ... }

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

[CustomPropertyDrawer(typeof(GenericclassInt))]
[CustomPropertyDrawer(typeof(GenericclassFloat))]
public class GenericclassDrawer: PropertyDrawer { ... }

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐