Pause and UnPause a Rigidbody in Unity 2

Nerd stuff ahead.  I needed to freeze a Rigidbody attached to an Object during a scene transition and then unfreeze and maintain the same velocity after the scene has finished loading. It sounds simple but Unity does not appear to have pausing/resuming functionality natively on a Rigidbody. You may be thinking that Sleep or WakeUp functions will help you; They will not. And setting an object isKinematic destroys velocity variables.

The most elegant solution I came up with was a class extension for Rigidbody that would store and recover key variables. With this file present anywhere in your project, you can call rigidbody.Pause() and rigidbody.UnPause() without having to make any new object references.

#RigidBodyExtension.cs
using UnityEngine;
using System.Collections;

public static class RigidbodyExtension  {

	static Vector3 velocity;
	static Vector3 angularVelocity;

	public static void Pause(this Rigidbody rb)
	{
		velocity = rb.velocity;
		angularVelocity = rb.angularVelocity;
		rb.isKinematic = true;

	}
	public static void UnPause(this Rigidbody rb)
	{
		rb.isKinematic = false;
		rb.velocity = velocity;
		rb.angularVelocity = angularVelocity;
	}
}

Please take a moment to read this!

Did this article help you out?  I'm a tech writer and I do this in my free time. The way I make money is when attractive people like you support me by buying me a beer, or by choosing to keep your data safe with a competitively priced off-site backup solution that I personally use. You can also sign up for Robinhood and Webull and we both get free stocks. (My friend won $168 in JPMorgon stock when I invited her.) Deposit $100 and you typically get more free stock. Want more? Head over to my About Page and try out one of the many links I've listed there.

2 thoughts on “Pause and UnPause a Rigidbody in Unity

  1. Pingback: FastTrick - Pause rigidbody simulation - Aliasing Games

  2. Reply Ohira Kyou (@OhiraKyou) Apr 3,2017 12:50 pm


    There’s a serious pitfall here: the temporary velocity and angularVelocity values are shared, meaning that pausing two or more rigidbodies will cause the wrong original velocities to be assigned. For future visitors, here’s my solution that uses a dictionary to manage velocities:

    RigidbodyExtensions.cs – https://gist.github.com/OhiraKyou/c98ec855fa97c8fce88955174c8d2894
    CollectionExtensions.cs – https://gist.github.com/OhiraKyou/45c5e2c131827776ba53f847936288d4

Leave a Reply

  

  

  

This site uses Akismet to reduce spam. Learn how your comment data is processed.

My ads are tame because I respect you. Please disable your adblocker or whitelist this site!