I have a class sleepingBody that do stuff when the attached rigidbody is Asleep.
At the moment, my check is very heavy because it runs at every FixedUpdate, checking if the rigidbody is fallen asleep.
There is some event that I can subscribe to that fire when a certain rigidbody is fallen Asleep?
General question: How can I “listen” to “system” variable, like rb.IsSpeeping, rb.IsKinematic, etc?
Thank you!!
My example code:
void FixedUpdate()
{
if rigidbody.IsSleeping == true{
sleepingBody(); //call method
}
}
void sleepingBody()
{
// do stuff
}
Please don’t say things are your “actual code” if it’s not your actual code. FixedUpdate is misspelled and you’re missing some parentheses. If that IS your actual code, you’ve got multiple problems to solve before even looking at the problem you’re posting about.
But to answer your question I don’t know of any way to get notified of a rigidbody sleeping or waking besides just checking that
I don’t know of any built-in event-based way of doing this. Do you need to know exactly the moment the object falls asleep, or just approximately? If it only needs to be approximate, you could make some kind of manager object which knows about all of your “sleepable” objects and spreads out these checks across different frames for different objects.
For example let’s say you have three objects that might sleep, A, B, and C. You might keep them in a list and only check one object in the list per frame for example. (If you have a lot of objects you might have to increase that number a bit, but the principle is the same. This will limit the number of sleep checks by a lot, but still give you notifications when the object is asleep.
Checking a boolean property every frame is “heavy?” Are you sure? Have you attached the profiler and seen a lot of time being spent in the IsSleeping() function? This seems … unlikely.
Generally, don’t optimize unless there is a problem.
And NEVER optimize until you measure and find where the problem is using the Profiler window.
“Listening to a variable” is not a built-in concept in C#. That would basically require the compiler to implicitly create an event for every variable in the entire program, which in most cases would be massive overkill.
You can look in the scripting API to see if it happens to have an event similar to what you’re looking for.
If there is no event, but you need to know anyway, then polling is the way to do it. “Polling” in this context refers to just looking at the variable every so often to see what it’s current value is, e.g. by checking in Update.
For things that change infrequently, polling is probably less efficient than events. But polling is still used all over the place, it’s a very common thing, it’s not a sign that you must have done something wrong. You can have tons of polling in a game without it actually becoming a performance problem.