Pause Your Unity 2D Rigid Bodies

Written by lordcodes | Published 2016/12/13
Tech Story Tags: csharp | unity | game-development

TLDRvia the TL;DR App

It is a feature most games will have, being able to pause the game. For most parts of the game it can be implemented by simply not updating positions or preventing logic from being executed. However, many objects will be controlled through physics or may be moving around automatically.

Whilst developing a game I came across this situation and to solve the problem wrote a simple C# script to pause and resume any RigidBody2D.

<a href="https://medium.com/media/004b5da622d8d00d0d93ad9fac427460/href">https://medium.com/media/004b5da622d8d00d0d93ad9fac427460/href</a>

When you call Pause() the velocity and angular velocity is saved and the body made kinematic, preventing the physics object from moving anymore. If you wish to just re-enable the physics you can call Reactivate() and then apply some forces to the body. Alternatively, a call to Resume() will restore the velocity and angular velocity from before and then resume it.

Now when you pause and resume your game you can simply call pause and resume on any PausableRigidBody2D objects which are active in view.

Enjoy!


Published by HackerNoon on 2016/12/13