Unity 的内置序列化程序可能需要做很多工作,但我真的只是在编写编辑器脚本时遇到了非常头疼的问题。就像,我非常同情this 家伙的愤怒。运行时序列化有点不同,使用起来更容易一些,尤其是在 Unity 的 JsonDotNet 等外部工具的帮助下,或者我看到你在其他地方提到过 SharpSerializer。还有FullSerializer 和它的资产商店分支FullInspector,专门用于帮助解决那些令人沮丧的编辑器脚本问题。
需要注意的几点:Unity 确实支持 UnityEngine.Object 派生类的多态性,这当然包括 MonoBehaviour。至于自定义类,如果这些类具有默认情况下unity无法序列化的属性(例如Dictionary),则可以实现ISerializationCallbackReciever接口。否则,您只需将 [Serializeable] 标记添加到类中,让 unity 知道您希望保存该数据。您还应该熟悉其他一些注意事项,请参阅:https://blogs.unity3d.com/2014/06/24/serialization-in-unity/
以您的用例为例,通常的结构可能如下所示:
[Serializeable]
public Class ActorProperties{
public int CurrentHealth;
public int MaxHealth;
public int Range;
}
public Class Actor : MonoBehaviour{
[SerializeField] protected ActorProperties _actorProperties
public ActorProperties ActorProperties{
get{ return _actorProperties;}
set{_actorProperties = value;}
}
}
public Class Character : Actor{
// Character specific code
}
public Class Enemy : Actor{
// Enemy specific Code
}
public Class GameManager : MonoBehaviour{
private List<Actor> enemies;
private List<Actor> characters;
public List<Actor> AllActors{
get{
List<Actor> returnList = new List<Actor>(characters);
returnList.AddRange(enemies);
return returnList;
}
}
public Actor GetActorWithHealth(float healthCheck){
Actor actor = AllActors.Find(x => x.ActorProperties.CurrentHealth == healthCheck);
return actor;
}
}
除了非序列化数据类型,下面的示例说明了需要自定义序列化的最常见实例。
// Even though Properties is marked as Serializeable, it's 'data' property
// won't get serialized if we're serializing a reference to an ActorProperties.
// No native support for polymorphic serialization of custom classes.
[Serializable]
public class Properties{
public float data;
}
[Serializeable]
public class ActorProperties : Properties{
// Here we have a recursion problem because Unity cannot serialize
// null values for custom classes. Unity will try to serialize this ActorProperties field, which in turn starts the serialization over again,
// with an iteration depth of 7. Killer if it were a List<ActorProperties> .
public ActorProperties EnemyProperties;
public int CurrentHealth;
public int MaxHealth;
public int Range;
// Since Unity treats custom classes like structs, the following field wont be serialized
// as a pointer to an existing object, but as a unique instance of it's class.
public CustomClass SharedReference;
}
像 Json.NET for Unity 等序列化解决方案。人。在使序列化过程更容易方面大有帮助,但无论您使用什么解决方案,关注数据将如何被序列化都非常重要。
我个人会为 Unity 推荐 Json.Net,但我使用过的唯一其他资产是 FullSerializer 和 FullInspector。我没用过SharpSerializer。