public class RigidbodyPauser
{
#region Types.
/// <summary>
/// Data for a rigidbody before being set kinematic.
/// </summary>
private struct RigidbodyData
{
/// <summary>
/// Rigidbody for data.
/// </summary>
private Rigidbody _rigidbody;
/// <summary>
/// Cached velocity when being set kinematic.
/// </summary>
private Vector3 _velocity;
/// <summary>
/// Cached velocity when being set kinematic.
/// </summary>
private Vector3 _angularVelocity;
public RigidbodyData(Rigidbody rigidbody)
{
_rigidbody = rigidbody;
_rigidbody.collisionDetectionMode = CollisionDetectionMode.ContinuousSpeculative;
_velocity = Vector3.zero;
_angularVelocity = Vector3.zero;
}
/// <summary>
/// Sets isKinematic status and returns if successful.
/// </summary>
public bool SetIsKinematic(bool isKinematic)
{
if (_rigidbody == null)
return false;
if (isKinematic)
{
_velocity = _rigidbody.velocity;
//_VELOCITY was being set to the wrong object hashcode if it contained anything other than Vector3.zero.
_angularVelocity = _rigidbody.angularVelocity;
_rigidbody.isKinematic = true;
}
else
{
_rigidbody.isKinematic = false;
_rigidbody.AddForce(_velocity, ForceMode.Impulse);
_rigidbody.AddTorque(_angularVelocity, ForceMode.Impulse);
}
return true;
}
}