Unity 2020.1可以序列化泛型类型,可编写以下代码来检查行为。
序列化通用类型
编写以下代码来检查行为。
using System;
using UnityEngine;
public class Example : MonoBehaviour
{
// 可以序列化泛型类实例
[SerializeField] private ExampleGeneric<int> _int;
[SerializeField] private ExampleGeneric<string> _string;
[SerializeField] private ExampleGeneric<Rect> _rect;
[SerializeField] private ExampleGeneric<AnimationCurve> _animationCurve;
}
// Serializable和Generic的类
[Serializable]
public class ExampleGeneric<T>
{
public T _testField;
}
如果将其附加到适当的游戏对象并显示检查器,则可以确认它已成功序列化。

到现在为止为了能序列化,制作了很多继承了Generic型的型的类,不过,那个必要没有了。
不能用于SerializeReference
以为也可以兼容SerializeReference属性,但是没有用。
using System;
using UnityEngine;
public class Example : MonoBehaviour
{
// SerializeReferenceはダメ
[SerializeReference] private ExampleGeneric<ExampleElement> _example;
}
[Serializable]
public class ExampleGeneric<T>
{
public T _testField;
}
public class ExampleElement
{
}
可以从下文了解SerializeReference。
收到了这样的错误:泛型类型似乎仍然不支持SerializeReference。
The field Example._example has the [SerializeReference] attribute applied, but is of type ExampleGeneric<ExampleElement>, which is a generic instance type. This is not supported. You must create a non-generic subclass of your generic instance type and use that as the field type instead.
…
以上是关于序列化通用类型的全部内容,如果你有任何反馈,请随时在本页面下方留言。