I'm working with Unity and I am trying to create a class that can store specific components states and restore them at a later stage. This is however not tied to Unity and should be able to be used anywhere with any type of property. This is however the example I will use since it is intuitive and the solution to that example should give a complete answer.
I have a GameObject
which has an object of the type Transform
attached to it which stores the location, rotation and scale of the object. This is what I would like to store and be able to restore at a later time.
Storing the state
The state of the object is saved by creating a deep copy of the Transform
and is then saved in a dictionary with the type as key, and the copy as value. The deep copy can be achieved by either via a Serializable
class or an Object
extension. Mind that using IClonable
is not possible since I do not own the code of the class Transform
. Using the Object
extension the code is easy. Inside a class:
// The object that should have its state (re)stored
public GameObject _parent;
// Dictionary to hold the object state and its underlying type
public Dictionary<Type, object> _states;
// Store a deep copy of the component of type T
public void StoreState<T>() {
_states.Add(typeof(T), _parent.GetComponent<T>().Copy());
}
// Alternatively
public void StoreState(Type t) {
_states.Add(t, _parent.GetComponent(t).Copy());
}
Restoring the state
This is the part where I am stuck. I cannot simply create a new instance of the Transform
and assign it to the GameObject
since its not accessible. How do I copy all values from the dictionary values back?
public void RestoreInitialState() {
foreach (var pair in _states) {
// Copy to original?
_parent.GetComponent(pair.Key) = pair.Value.Copy();
// Error: The left-hand side of an assignment must be a variable, property or indexer
// This expression cannot be used as an assignment target
}
}
It might be sufficient to copy all public fields and/or properties?