Best way to prevent physics calculations in Unity from eating too much FPS?

671 Views Asked by At

I'm a senior software engineer, but completely new to Unity programming. I've been teaching myself Unity for a few weeks by writing some SteamVR toys for myself. I wanted to ask about Unity's standard built-in ways to improve frame rate for a program with a lot of intensive physics calculation.

In my current VR scene, I have a ball with a Rigidbody on it. When I pick it up and throw it, I let it move naturally, but I apply small forces on every Update() call to adjust the landing position and always hit a target.

I saw my framerate take a big dive, so I wrote my own function to throttle the updates, limiting them to 5 per second. The question is, is there some standard Unity behavior that I should be using instead of rolling this code myself?

In my throwing script, I maintain a bunch of top level variables and update them first to decide whether I should do calculations on the current frame.

private void updateCalculationFrame() {
    isCalculationFrame = Time.time > nextCalculationTime;
    while (nextCalculationTime < Time.time) {
        nextCalculationTime += (1 / calculationsPerSecond);
    }
}

On each frame, I run this function, then if isCalculationFrame is true, I proceed to calculate and add force vectors. I just wonder if I am overlooking some more standard way to do this with less code? I feel like this must be a very common thing to try to do.

1

There are 1 best solutions below

1
On

The code you have there will freeze the Unity until the loop is finished. You shouldn't do this at all.

You could simply set a new Time.fixedDeltaTime. By default it is usually about 0.02 but you can set it to anything you want.

The interval in seconds at which physics and other fixed frame rate updates (like MonoBehaviour's FixedUpdate) are performed.

...

Note that the fixedDeltaTime interval is with respect to the in-game time affected by timeScale.