# OnRigidbodyWakeUp

I know there isn’t an event called “OnRigidbodyWakeUp”, but I need an efficient way of calling a function every time when the rigidbody moves for any reason (like a collision or a force).

``````Update()
{
if (!rigidbody.IsSleeping())
doIt();
}
``````

Above code is working, but calling IsSleeping() every frame isn’t look so efficient. Do you think this is the best way?

No one?

maybe put it in LateUpdate or FixedUpdate?

You could do an add value between the rigidbody.velocity.magnitude and the rigidbody.angularVelocity.magnitude, and it if is over like 0.1 then it is not sleeping. That would be quick.

I don’t believe that isSleeping() would take up much processor power because it is set every Physics update anyways. If it is above x, it is awake, if not, it is sleeping.

If it was a read only variable, we could be sure of that. Maybe it is just a simple getter method for encapsulation. Checking angular and linear velocities can be much slower then.

Unity is a well documented engine but when it comes to optimization, it is like a black box…

Test it…

``````private var accum=Array();
var n = 0;

function Update () {
if(n < 100){
for(var i=0; i <1000000; i++){
var a=rigidbody.IsSleeping();
}
n=n+1;
print(Array(accum.length, Time.deltaTime));
} else if(n<101){
var t=0.0;
for(i=1; i<accum.length; i++){
t=t+ accum[i];
}
print("Average: " + (t/(accum.length-1)) + " over " + (accum.length - 1));
n=n+1;
}
}
``````

Thanks. It is really a good way to be sure
Here are the results…

With your code (“var a=rigidbody.IsSleeping();”)
Average: 0.2334862 over 99

Changed that line with this: “var a = rigidbody.velocity.sqrMagnitude;”
Average: 0.2959967 over 99

And with angular velocity
var a = rigidbody.velocity.sqrMagnitude;
var b = rigidbody.angularVelocity.sqrMagnitude;
Average: 0.3301686 over 99

Eventually, IsSleeping is faster than checking velocities