- Home /
Easy way to save rigidbody state.
Is there an easy way to save the state of a Rigidbody component (velocity, angular velocity, mass, etc.) so it can be loaded to a GameObject in the future?
For example: The player fires a gun, so a bullet is instantiated with a certain velocity, that may or may not stay the same. The player uses a save feature to save the game. Then, the player uses a load feature to restore the game state. I want the bullet to still have the same velocity as before, and not fall straight to the ground.
I tried serializing the Rigidbody component using a binary formatter, but it isn't marked as serializable.
Do I have to create a container class with all the rigidbody's variables and serialize that instead?
Thanks for helping :)
Do I have to create a container class with all the rigidbody's variables and serialize that ins$$anonymous$$d?
Yes you do. Hope this helps >.<
Yes, you have to create a container class, or write code that automatically gets all member values from the RB class. From looking at the Scripting API for the RB class, I get the impression that velocity and angularVelocity might be all that's needed,, provided that things like mass and drag don't change during runtime.
Answer by hexagonius · Sep 19, 2017 at 07:34 AM
If you have a script on the bullet, you can just extend the usual serialization for the rigidbody by implementing this interface:
https://docs.unity3d.com/ScriptReference/ISerializationCallbackReceiver.html