问题
I am trying to serialize an entire GameObject with Newtonsoft.Json. When I serialize the object with JsonConvert it throws an error:
NotSupportedException: rigidbody property has been deprecated
UnityEngine.GameObject.get_rigidbody () (at C:/buildslave/unity/build/Runtime/Export/UnityEngineGameObject_Deprecated.cs:23)
(wrapper dynamic-method) UnityEngine.GameObject.Getrigidbody (object) <IL 0x00006, 0x00073>
Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue (object) (at Assets/JsonDotNet/Source/Serialization/DynamicValueProvider.cs:104)
Rethrow as JsonSerializationException: Error getting value from 'rigidbody' on 'UnityEngine.GameObject'.
Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue (System.Object target) (at Assets/JsonDotNet/Source/Serialization/DynamicValueProvider.cs:108)
Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject (Newtonsoft.Json.JsonWriter writer, System.Object value, Newtonsoft.Json.Serialization.JsonObjectContract contract, Newtonsoft.Json.Serialization.JsonProperty member, Newtonsoft.Json.Serialization.JsonContract collectionValueContract) (at Assets/JsonDotNet/Source/Serialization/JsonSerializerInternalWriter.cs:338)
Why is that happening?
There is problem in here:
public object GetValue(object target)
{
try
{
if (_getter == null)
_getter = DynamicReflectionDelegateFactory.Instance.CreateGet<object>(_memberInfo);
return _getter(target);
}
catch (Exception ex)
{
throw new JsonSerializationException("Error getting value from '{0}' on '{1}'.".FormatWith(CultureInfo.InvariantCulture, _memberInfo.Name, target.GetType()), ex);
}
}
It's a part of DynamicValueProvider.cs
回答1:
I don't know about Newtonsoft.Json, but judging from the error message - GameObject property rigidbody
has been deprecated in Unity 5 along with some other common property getters, see here and here.
All calls to rigidbody
must be replaced with GetComponent<Rigidbody>()
instead.
回答2:
The error message is spurious. It happens because of the way JsonConvert performs serialisation, by working its way through all the properties. It's more or less random which one fails first.
The real problem is that classes derived from MonoBehaviour cannot be simply serialised. You need to work out a way to just serialise the data values you are interested in, not the whole class.
Search on 'serialise MonoBehaviour' to get some ideas how to do that. The recommended way is to use a ScriptableObject.
来源:https://stackoverflow.com/questions/31786488/unity-5-gameobject-serialization