Trying to use JsonUtility.ToJson(transform) results in a runtime error: | ArgumentException: JsonUtility.ToJson does not support engine types.
Why is this a thing? Why am I not allowed to use this on engine classes in a final release build? I can’t see any logical reason for this to be only allowed on self-implemented mono-behaviours.
The reason why I want this, is for example to save the initial Transform of an object so I can reset its position/rotation/transform to its original state. Yes I can copy the variables, but I want a more general approach so any component can be stored without the need to define all variables you wish to save for every single component. JsonUtility seems to do a good job of filtering out only the needed data.
The Transform class does not derive from MonoBehaviour or ScriptableObject but from Component.
Maybe that can help you (if you doing it inside the editor).
a not so nice but workable way would be to create a custom struct that can contain all the transforms data and the you can save and write back the data on will.
All of the component classes needs to be attached to a GameObject to work. A transform doesn’t really make sense on it’s own - which means that serializing a Transform only serialized half of a compound object.
Now, it would make sense if ToJson and FromJsonOverwrite worked with engine objects, while FromJson threw an error, which is what it sounds like you’re doing. Unity probably didn’t see that, or thought that the overhead for solving this problem was too hard.
If you want to save the initial state of a Transform, you should probably do that manually. This thread has some details.
Thanks for the answers, sadly none of them seem to be answer my question. To reiterate: I want a robust method I only have to implement once and works for every single class. The way I could for example use the following code:
private string _json;
public void Save<T>(GameObject obj) {
_json = JsonUtility.ToJson(obj.GetComponent<T>());
}
public void Restore<T>(GameObject obj) {
JsonUtility.FromJsonOverwrite(_json, obj.GetComponent<T>());
}
This code works for any self-implemented Mono-Behaviour.
After some more research I came across this answer, which tells us that, at its core, Unity is implemented in C++, meaning the engine classes are not actual C# classes. It’s just the way we interact with them. This in turn means the Transform class cannot be ‘seen’ in C# making it possibly impossible to efficiently save these types of classes.
I’ve also checked with reflection and the class Transform does not contain any field, not even auto-properties. None of these variables are thus saved in C# which makes it impossible to have the code streamlined like the above example. So as far as I understand it,
I wanted to let everyone with the same problem know there is a new correct answer, and it is to use runtime scene serialization! I’ve posted about it here !