- Home /
Why does Rigidbody.OnDisable() reset the velocity?
If you call gameObject.SetActive(false) on an object with a Rigidbody2D, and later SetActive(true), the object will lose its velocity and angular velocity. This consistently happens to me when there's a frame delay between deactivating and re-activating the object (won't work if you immediately call SetActive(true) afterward).
note that changing rigidbody.simulated to false and then true will NOT reset the velocity.
I suspect that this also happens with regular Rigidbody but I only tested this with 2D physics.
This is frustrating, unexpected, unintuitive behavior. Why doesn't it just freeze the velocities until it is reactivated?
Can I find a workaround that does not require me to cache the velocities with a new component (or in a big table somewhere)?
Answer by TheSOULDev · Aug 26, 2017 at 04:03 PM
Frustrating maybe for you, but certainly not unexpected or unintuitive. Think of how much of a bother object pooling would be if you'd have to keep track of physics attributes. If the velocity is not removed, how would Unity keep the object from moving? Or, if it kept moving and OnEnable set it to the original location, how would unity know what location it is without back tracking and recording additional values? The things you want are completely unnecessary, unintuitive and unoptimized.
Setting an object inactive means treating it as non-existent. If it's non-existent, it doesn't travel, and if it's not travelling, it has no velocity.
Meanwhile you, as a programmer, can alter this behaviour. Having rigidbodies tax the game unnecessarily for people who don't need this kind of behaviour would be blasphemous.
Right, active physics objects (aka Rigidbodies) have a representation inside the physics system. When you deactivate an object it's no longer being part of the physics system. At the next physics update (FixedUpdate) the system will detect that the object is deactivated and will remove it from the system. The same happens with colliders.