Hackernoon logoPause Your Unity 2D Rigid Bodies by@lordcodes

Pause Your Unity 2D Rigid Bodies

Andrew Lord Hacker Noon profile picture

@lordcodesAndrew Lord

Mobile Lead Developer

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.

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.



Join Hacker Noon

Create your free account to unlock your custom reading experience.